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 回复

应该是js精度丢失导致的 根uniapp没关系 自定义一个四舍五入方法就行了 //自定义四舍五入
function toFixedCustom(num, precision) {
const factor = Math.pow(10, precision);
return (Math.round(num * factor) / factor).toFixed(precision);
}
console.log(toFixedCustom(0.855, 2)); // 输出 “0.86” 0.855 在二进制中是一个无限循环小数,实际存储值可能略小于 0.855(如 0.8549999999999999) 当第三位小数小于5时,会直接截断而非四舍五入。此时若实际值为 0.854999…,第三位是4,结果即为 0.85。


在谷歌浏览器控制台打印就是0.85了。。不关uniapp的事,可以用楼上的办法。 也可以使用 Number(0.855).toLocaleString(‘zh’, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}) 嘛,这个方法会表示成千分位的,还需要.replace(/,/g, ‘’),哈哈

这是JavaScript浮点数精度问题的典型表现。在JS中,0.855实际上存储为0.85499999999999998,因此toFixed(2)会四舍五入为0.85。

解决方案:

  1. 使用Number.EPSILON修正:
console.log((0.855 + Number.EPSILON).toFixed(2)) // 0.86
  1. 自定义四舍五入函数:
function round(value, decimals) {
  return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals)
}
console.log(round(0.855, 2)) // 0.86
回到顶部