JavaScript Number.toFixed(2),未按预期四舍五入。这是错误吗?

时间:2019-10-29 05:29:53

标签: javascript rounding rounding-error tofixed

我当时正在编写需要四舍五入和数字格式的代码,并且在编写单元测试时遇到了这种奇怪的情况。有时Number.toFixed()不能按预期四舍五入。进一步的调查表明,舍入逻辑在数字64处发生了变化。这是我在v2.0.0

上运行的示例
function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// expected output: "123.46"

console.log(financial(0.004));
// expected output: "0.00"

console.log(financial(0.005));
// expected output: "0.01"

console.log(financial(10.005));
// expected output: "10.01"

console.log(financial(63.005));
// expected output: "63.01" <<== This is still OK.

console.log(financial(64.005));
// expected output: "64.01" <<== THIS RETURNS 64.00, NOT 64.01. WHY?

console.log(financial(100.005));
// expected output: "100.01"  <<== THIS RETURNS 100.00, NOT 100.01. WHY?

console.log(financial(64.006));
// expected output: "64.01"  <<== This is OK as well

console.log(financial(64.015));
// expected output: "64.02"  <<== This is OK as well

console.log(financial(64.105));
// expected output: "64.11"  <<== This is OK as well

console.log(financial('1.23e+5'));
// expected output: "123000.00"

从代码输出以及未包括的其他一些测试中,如果以十进制表示的两个前导零以及数字5,则从数字64和更大的数字开始,似乎不发生于toFixed(2)。我没有尝试使用toFixed(3)和3个前导零。 但是,如果小数点中有任何非零数字,则四舍五入会正确发生。 但是,数字64.006正确舍入为64.01

由于某些原因,我不了解这种舍入行为吗? 有什么解决办法吗?

谢谢。

0 个答案:

没有答案