我正在编写需要一些舍入和数字格式的代码,并且在编写单元测试时遇到了这个奇怪的情况。有时 Number.toFixed() 不会按预期四舍五入。进一步调查显示,数字 64 处的舍入逻辑发生了变化。这是我在MDN Number.toFixed() 文档站点上运行的示例。
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"
从代码输出和其他一些未包含的测试来看,似乎从数字 64 和任何更大的数字开始,如果小数点后有两个前导零,后跟数字 5,则 toFixed 不会发生四舍五入(2)。我没有尝试使用 toFixed(3) 和 3 个前导零。但是,如果小数中有任何非零数字,则舍入正确。然而,数字 64.006 正确舍入为 64.01
由于某种我不明白的原因,这种舍入行为是预期的吗?有什么解决方法吗?
谢谢。