我在处理数字舍入方面遇到了问题。
x = 0.175;
console.log(x.toFixed(2));
// RESULT: 0.17
x = 1.175;
console.log(x.toFixed(2));
// RESULT: 1.18
x = 2.175;
console.log(x.toFixed(2));
// RESULT: 2.17
我在处理数字舍入方面遇到了问题。
x = 0.175;
console.log(x.toFixed(2));
// RESULT: 0.17
x = 1.175;
console.log(x.toFixed(2));
// RESULT: 1.18
x = 2.175;
console.log(x.toFixed(2));
// RESULT: 2.17
这就是背后的原因...
将无限多的实数压缩到有限数量的比特中需要进行近似表示。
虽然整数有无限多个,但在大多数程序中,整数计算的结果可以存储在32位中。
相比之下,对于任何固定数量的比特,大多数实数计算将产生无法使用那么多比特精确表示的量。因此,浮点计算的结果通常必须舍入以适应其有限表示。
x = 0.175;
console.log(x.toFixed(20));
// RESULT: 0.17
x = 1.175;
console.log(x.toFixed(20));
// RESULT: 1.18
x = 2.175;
console.log(x.toFixed(20));
// RESULT: 2.17
这个舍入误差是浮点计算的特征。
来源:http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
http://www.jacklmoore.com/notes/rounding-in-javascript/
即使在JavaScript中更精确地控制浮点表示,也无法解决这个问题:
> x=2175e-3; x.toFixed(2);
"2.17"
> x=1175e-3; x.toFixed(2);
"1.18"
*.18
的东西。 - Nina ScholztoFixed(20)
,你就会明白为什么了。 - georg