我在使用 toFixed 时遇到了四舍五入的错误。
我用了 toFixed(2)
在我的数值计算中,但在少数情况下,四舍五入的结果并不尽如人意。
假设 toFixed(2)
适用于价值 17.525
那么它的结果是 17.52
如果它被申请 5.525
那么它的结果是 5.53
.
在后一种情况下,四舍五入的结果是准确的,所以请你建议需要做什么才能得到后一种情况下的准确四舍五入结果。或者你能不能建议一个替代toFixed函数的方法来获得正确的四舍五入结果?
浮点数不准确意味着大多数以0.525结尾的数字实际上是0.52500...1,而其他数字是0.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
将数字转换为String,然后用它工作?
这是我尝试使用Math.round,或用Math.ceil模拟最近的四舍五入,但失败后的最后手段。当与100相乘时,一些数字(如17.525)会比其值的100倍(1752.5)少一点,而其他数字(如17.545)会比其值的100倍(1754.5)多一点。
使用 编码格式 并在选项中设置 minimumFractionDigits
和 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