//原数据测试
console.log(1.315.toFixed(2))
console.log(1.325.toFixed(2))
console.log(1.335.toFixed(2))
console.log(1.345.toFixed(2))
console.log(1.355.toFixed(2))
console.log(1.365.toFixed(2))
console.log(1.375.toFixed(2))
let sum = 0.1 + 69.925
console.log('sum', sum)
console.log('sum', sum.toFixed(2))
console.log('------------')
解决方法
//格式化浮点数
function formatFloat(num) {
if (!Number.prototype._toFixed) {
Number.prototype._toFixed = Number.prototype.toFixed
}
Number.prototype.toFixed = function (n) {
return (this + 1e-14)._toFixed(n)
}
return Number(num).toFixed(2)
}
console.log(formatFloat(1.315)) //0.32
console.log(formatFloat(1.325)) //0.33
console.log(formatFloat(1.335)) //0.34
console.log(formatFloat(1.345)) //0.35
console.log(formatFloat(1.355)) //0.36
console.log(formatFloat(1.365)) //0.37
console.log(formatFloat(1.375)) //0.38
console.log('处理后的sum', formatFloat(sum))
在chrome和ie中均测试满足要求,可以把上边的两段代码直接粘在chrome\ie的控制台里测试。
在执行过这个方法之后的toFixed(2)可以正确输出。所有不要在用过这个方法之后再测了。
方法原网站
各位测出有问题的欢迎留言指正!