首页 > 解决方案 > toFixed rounds at 6 为什么不是 5?

问题描述

我预计50.65.toFixed(1)会返回"50.7",因为它以 0.05 舍入,但得到了"50.6"

我测试了另一种情况:50.66.toFixed(1)它返回'50.7'.

为什么不是5轮?有任何想法吗?

我已阅读TC39,但未能理解。

console.log(100.15.toFixed(1)) // 100.2 (OK)
console.log(123.45.toFixed(1)) // 123.5 (OK)
console.log(50.65.toFixed(1)) // 50.6 (what??)

标签: javascript

解决方案


的舍入方法toFixedhttps://tc39.es/ecma262/#sec-number.prototype.tofixed中描述为“让 n 是一个整数,其中 n / 10^f - x 尽可能接近零。如果有两个这样的n,选择较大的n。”

并且506 / 10 - 50.65比接近于零507 / 10 - 50.65

您可以使用以下方法对其进行测试:

if (Math.abs(506 / 10 - 50.65) < Math.abs(507 / 10 - 50.65)) {
    console.log(1);
} else {
    console.log(2);
}

1001 / 10 - 100.15不比1002 / 10 - 100.15

if (Math.abs(1001 / 10 - 101.15) < Math.abs(1002 / 10 - 101.15)) {
    console.log(1);
} else {
    console.log(2);
}

因此它是四舍五入。


推荐阅读