toFixed(2) 对 “x.525” 的舍入不一致
toFixed(2) rounds "x.525" inconsistently?
我在使用 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 倍。
使用国际数字格式,并在选项中将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
相关文章:
- 当属性不一致时,如何根据属性对JS对象列表进行排序
- 淡入不带HTML的背景图像
- 浮点0.2+0.1舍入误差
- 如何在不向上舍入的情况下删除尾随小数
- 在javascript中不带舍入的十进制比较
- Firefox setTimeout + jQuery 淡入淡出循环不一致,提前停止,不会循环
- 如何处理下拉列表的十进制值而不舍入或修剪零
- toFixed(2) 对 “x.525” 的舍入不一致
- 添加用户输入而不舍入(Google Apps 脚本)
- JavaScript:在不影响结果准确性的情况下舍入数字
- 如何使用 javascript 获取带有 2 个小数且不舍入的数字
- 如何使用javascript截断(不舍入)小数点后的特定数字
- 这 === 是否不适用于浮点舍入不准确的 b/c
- 大的 JavaScript ints 不会在没有舍入的情况下转换为 String
- 舍入javascript字符串并显示不带小数的美元格式
- JavaScript舍入不起作用
- 在Javascript中将双精度型转换为整型,不需要舍入
- Javascript乘法不正确,导致不正确的舍入
- Lodash舍入到小数点后1位而不是2位
- 是否存在不舍入的小数数据类型?