使用js计算过程中,会存在精度问题,比如:
- 浮点数的计算:
- 0.1 + 0.2 != 0.3
- 1.1 * 100 != 110
- 大数精度问题:
- 9999 9999 9999 9999 == 1000 0000 0000 0000 1
- toFixed 四舍五入结果不准确:
- 1.335.toFixed(2) == 1.33
本文只解决浮点数计算的精度问题
解决计算精度问题的思路
常见解决思路主要有:
// 获取小数位的长度
function digitLen(num) {
let decimal = num.toString().split('.')[1]
if (decimal) return decimal.length
return 0
}
function calc(a, operation, b) {
// 算出最小的,能将两个数转换为整数的10的次方
let common = 10 ** (Math.max(digitLen(a), digitLen(b)))
let res;
switch (operation) {
case '+': // 加
res = (a * common + b * common) / common
break
case '-': // 减
res = (a * common - b * common) / common
break
case '*': // 乘
res = ((a * common) * (b * common)) / common ** 2
break
case '/': // 除
res = ((a * common) / (b * common))
break
}
// 利用toFixed四舍五入,解决类似:(0.11*100*1.1*100)/10000 计算不准确的问题(某些浮点数乘10精度错误)
return parseFloat(res.toFixed(12))
}
// 测试代码
let res = calc(1.11, '*', 10)
console.log(res)