toFixed,我經(jīng)常用來四舍五入保留兩位小數(shù)诀拭,但是到今天我才真正意識到toFixed不是真的四舍五入迁筛,他是四舍六入!
比如
0.984.toFixed(2)
// 字符串0.98
0.985.toFixed(2)
// 神奇的打印的是字符串0.98耕挨,而不是我們想要的0.99
0.986.toFixed(2)
// 字符串0.99
我翻閱了好多技術(shù)社區(qū)细卧,比如某否,某金筒占,某乎贪庙,某書,大部分回答都是使用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漠趁,
我再也不相信任何人了扁凛,所以我就自己寫了一個(gè)四舍五入,希望有用棚潦,如果有問題請斧正
Number.prototype._toFixed = Number.prototype.toFixed
Number.prototype.toFixed = 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.toFixed(2)
// 0.99
0.145.toFixed(2)
// 0.15