0.855.toFixed(2) == 0.85 是错的 应该是0.86
0.855.toFixed(2) == 0.85 是错的 应该是0.86
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | 10 | HBuilderX |
示例代码:
console.log(0.855.toFixed(2))
操作步骤:
console.log(0.855.toFixed(2))
预期结果:
0.86
实际结果:
0.85
bug描述:
js的 0.855.toFixed(2) == 0.85
3 回复
在谷歌浏览器控制台打印就是0.85了。。不关uniapp的事,可以用楼上的办法。
也可以使用
Number(0.855).toLocaleString(‘zh’, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
嘛,这个方法会表示成千分位的,还需要.replace(/,/g, ‘’),哈哈
这是JavaScript浮点数精度问题的典型表现。在JS中,0.855实际上存储为0.85499999999999998,因此toFixed(2)会四舍五入为0.85。
解决方案:
- 使用Number.EPSILON修正:
console.log((0.855 + Number.EPSILON).toFixed(2)) // 0.86
- 自定义四舍五入函数:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals)
}
console.log(round(0.855, 2)) // 0.86