美文网首页前端大杂烩
JS toFixed之四舍五入

JS toFixed之四舍五入

作者: 写写而已 | 来源:发表于2021-11-05 15:07 被阅读0次

toFixed,我经常用来四舍五入保留两位小数,但是到今天我才真正意识到toFixed不是真的四舍五入,他是四舍六入!

比如

0.984.toFixed(2)
// 字符串0.98
0.985.toFixed(2)
// 神奇的打印的是字符串0.98,而不是我们想要的0.99
0.986.toFixed(2)
// 字符串0.99

我翻阅了好多技术社区,比如某否,某金,某乎,某书,大部分回答都是使用Math.round,乘以100,再除以100,就试了一下

Math.round(0.986 * 100) / 100
// 0.99
Math.round(0.985 * 100) / 100
// 0.99
Math.round(0.984 * 100) / 100
// 0.98
Math.round(0.945 * 100) / 100
// 0.95
Math.round(0.905 * 100) / 100
// 0.91

ok,完美!
但是,真的完美吗?然后我掏出0.145

Math.round(0.145 * 100) / 100
// 0.14

天啊这是怎么了?!我都不敢相信自己的眼睛,三观尽毁!
找了很多方法,大部分都是用Math.round(num * 100) / 100,
我再也不相信任何人了,所以我就自己写了一个四舍五入,希望有用,如果有问题请斧正

Number.prototype.newFixed = function (n = 2) {
    let temp = (this + '').split('.')
    if (!temp[1] || temp[1].length <= n) {
        return this.toFixed(n)
    } else {
        let nlast = temp[1].substring(n, n + 1)
        temp[1] = temp[1].substring(0, n) + (nlast >= 5 ? '9' : '1')
        return Number([temp[0], temp[1]].join('.')).toFixed(n)
    }
}
0.985.newFixed(2)
// 0.99
0.145.newFixed(2)
// 0.15

相关文章

网友评论

    本文标题:JS toFixed之四舍五入

    本文链接:https://www.haomeiwen.com/subject/rodrzltx.html