toFixed(2) 对 “x.525” 的舍入不一致

toFixed(2) rounds "x.525" inconsistently?

本文关键字:舍入 不一致 toFixed      更新时间:2023-09-26

我在使用 toFix 时遇到舍入错误:

我在数值计算中使用了toFixed(2),但在少数情况下,舍入结果与预期不同。

假设toFixed(2)应用于值17.525则给出结果17.52,如果应用于5.525则给出结果5.53

在后一种情况下,舍入结果是准确的,

因此您能否建议需要做些什么才能获得准确的舍入结果,就像后一种情况一样。或者您能否建议此 toFixed 函数的替代方案以获得正确的舍入结果?

点不准确意味着大多数以 .525 结尾的数字实际上是 .52500..1,而其他数字是 .5249999.....

舍入的方式取决于 IEEE-754 浮点中最接近的实际表示形式是高于还是低于所需值。

而不是toFixed()使用Math.ceil()Math.floor()Math.round()

有办法绕过像

var rnum = 5.525,
    decimalPlaces = 2,
    factor = Math.pow(10, decimalPlaces),
    newnumber = Math.round(rnum * factor) / factor,
    mydecimalvalue = parseFloat(newnumber); 

结果是5.53

将数字转换为字符串并使用它?

这是我尝试使用 Math.round 或使用 Math.ceil 模拟最接近的舍入但失败后的最后手段。当乘以 100 时,某些数字(例如 17.525)将略小于其值 (1752.5) 的 100 倍,而其他数字(例如 17.545)将略高于其值 (1754.5) 的 100 倍。

使用国际数字格式,并在选项中将minimumFractionDigitsmaximumFractionDigits设置为相同的数字(要显示的位数)。

const formatter = [0, 1, 2, 3, 4, 5].map(
    (decimals) =>
        new Intl.NumberFormat('en-US', {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals,
        }),
);
console.log(formatter[2].format(17.525)); // 17.53
console.log(formatter[2].format(5.525)); // 5.53
console.log(formatter[2].format(1.005)); // 1.01
console.log(formatter[2].format(8.635)); // 8.64
console.log(formatter[2].format(8.575)); // 8.58
console.log(formatter[2].format(35.855)); // 35.86
console.log(formatter[2].format(859.385)); // 589.39
console.log(formatter[2].format(859.3844)); // 589.38
console.log(formatter[2].format(.004)); // 0.00
console.log(formatter[2].format(0.0000001)); // 0.00
// keep in mind that this will not be formatted as expected, as the value that
// you pass is actually 0.07499999999998863. 
console.log(formatter[2].format(239.575 - 239.5)); // 0.07
console.log(formatter[2].format(0.07499999999998863)); // 0.07