javascript - 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??)
解决方案
的舍入方法toFixed
在https://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);
}
因此它是四舍五入。
推荐阅读
- asp.net-core - ASP.Net 核心 - IdentityModelEventSource 日志文件在没有发布的情况下运行在哪里?
- javascript - 更改文件格式
- excel - 将列单元格分成 2-3 组的 3 列?
- tabulator - 日期和时间选择器作为制表器中的自定义编辑器
- python - While & Sentinel 价值观
- javascript - 表单提交问题后Ajax重新加载DIV
- java - 构建应用程序时多表主键 JPA 上的 NullPointerException
- javascript - 开玩笑地模拟 uuid - 在服务函数中调用 uuid
- qt - 如何在悬停时更改 QML 中对象的属性?
- python - 我无法让 AWS S3 在我的 Django/Heroku 应用程序上提供媒体文件