toFixed精度不准问题
首先toFixed并不是网上说的使用银行家舍入法(四舍五入,五看奇偶)原则
如想了解银行家舍入法,在文章末尾
1、问题描述:
测试以下例子可见:toFixed()不是四舍五入,也不是银行家舍入法,所得结果不准确,不是我们想要的
console.log(3.1349046546.toFixed(2)) // 3.13,当舍去位的数值 < 5时,直接舍去
console.log(3.1369046546.toFixed(2)) //3.14,当舍去位的数值 >= 6时,在舍去的同时向前进一位
console.log(3.1351.toFixed(2) ) //3.14,当舍去位的数值 = 5时,后不为空且不全为0,舍去的同时向前进一位
console.log(3.1350000000000001.toFixed(2)) //3.14,当舍去位的数值 = 5时,后不为空且不全为0,舍去的同时向前进一位
console.log('++++++++++++++++++++++++++')
//当舍去位的数值 = 5时,5后为空或全为0,5前数值为奇数,并没有全部向前进一位,只有1向前进了一位
console.log(3.115.toFixed(2)) //3.12
console.log(3.135.toFixed(2)) //3.13
console.log(3.155.toFixed(2)) //3.15
console.log(3.175.toFixed(2)) //3.17
console.log(3.195.toFixed(2)) //3.19
console.log(3.1150.toFixed(2)) //3.12
console.log(3.1350.toFixed(2)) //3.13
console.log(3.1550.toFixed(2)) //3.15
console.log(3.1750.toFixed(2)) //3.17
console.log(3.1950.toFixed(2)) //3.19
console.log('++++++++++++++++++++++++++')
//当舍去位的数值 ) = 5时,5后为空或全为0,5前数值为偶数,并没有全部舍去
console.log(3.105.toFixed(2)) //3.10
console.log(3.125.toFixed(2)) //3.13
console.log(3.145.toFixed(2)) //3.15
console.log(3.165.toFixed(2)) //3.17
console.log(3.185.toFixed(2)) //3.19
console.log(3.1050.toFixed(2)) //3.10
console.log(3.1250.toFixed(2)) //3.13
console.log(3.1450.toFixed(2)) //3.15
console.log(3.1650.toFixed(2)) //3.17
console.log(3.1850.toFixed(2)) //3.19
结果如下图:
2、解决方案:
方法一:自行封装函数
(1)直接在原型上修改,仍然使用原调用方式
data() {
Number.prototype.toFixed= function (exponent) {
console.log(123)
return parseInt(this * Math.pow(10, exponent) + 0.5) / Math.pow(10, exponent);
}
return {}
},
(2)使用方法调用
function toFixed(num, s) {
var times = Math.pow(10, s)
var des = num * times + 0.5
des = parseInt(des, 10) / times
return des + ''
}
此方法是从网上粘贴的,如有需要可 自行百度封装方法
方法二:使用Math.round()代替
例如:
保留两位小数:Math.round(15.7784514000 * 100) / 100 ===》15.78
保留三位小数:Math.round(15.7784514000 * 1000) / 1000 ===》15.778
Math.round()是四舍五入到最接近的整数:该例子也就是先乘以10的n次方,然后四舍五入,然后除以10的n次方
小数乘法也会存在精度问题,具体讲解可以看我的另一篇文章js小数运算精度丢失问题 但是这里能满足需求了
银行家舍入法:
其实质是一种【四舍六入五取偶】的方法。
规则是:
当舍去位的数值 < 5时,直接舍去
当舍去位的数值 >= 6时,在舍去的同时向前进一位
当舍去位的数值 = 5时:
(1)5后不为空且不全为0,在舍去的同时向前进一位
(2)5后为空或全为0:
① 5前数值为奇数,则在舍去的同时向前进一位
② 5前数值为偶数,则直接舍去