7

使用 toFixed 时遇到舍入错误:

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

假设它toFixed(2)被申请价值17.525然后它给出结果17.52,如果它被申请5.525那么它给出结果5.53

在后一种情况下,舍入结果是准确的,所以请您建议需要做什么才能获得后一种情况下的准确舍入结果。或者您能否建议这个 toFixed 函数的替代方法以获得正确的舍入结果?

4

4 回答 4

5

浮点数不准确意味着大多数以 0.525 结尾的数字实际上是 0.52500..1,而其他数字是 0.5249999.....

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

于 2012-05-26T17:06:48.340 回答
3

而不是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

于 2012-05-26T17:17:56.363 回答
1

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

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

于 2012-05-26T17:02:56.187 回答
1

使用Intl.NumberFormatminimumFractionDigits并在选项集中设置maximumFractionDigits为相同的数字(要显示的位数)。

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

于 2020-05-28T13:04:35.093 回答