使用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

本文只解决浮点数计算的精度问题

解决计算精度问题的思路

常见解决思路主要有:

  1. 采用toFixed四舍五入,比如将0.1+0.2的结果进行四舍五入
  2. 将浮点数转换为整数计算
  3. 将数字转为字符串,模拟计算

    封装函数

    本函数主要采用第1和第2种解决方案

  1. // 获取小数位的长度
  2. function digitLen(num) {
  3. let decimal = num.toString().split('.')[1]
  4. if (decimal) return decimal.length
  5. return 0
  6. }
  7. function calc(a, operation, b) {
  8. // 算出最小的,能将两个数转换为整数的10的次方
  9. let common = 10 ** (Math.max(digitLen(a), digitLen(b)))
  10. let res;
  11. switch (operation) {
  12. case '+': // 加
  13. res = (a * common + b * common) / common
  14. break
  15. case '-': // 减
  16. res = (a * common - b * common) / common
  17. break
  18. case '*': // 乘
  19. res = ((a * common) * (b * common)) / common ** 2
  20. break
  21. case '/': // 除
  22. res = ((a * common) / (b * common))
  23. break
  24. }
  25. // 利用toFixed四舍五入,解决类似:(0.11*100*1.1*100)/10000 计算不准确的问题(某些浮点数乘10精度错误)
  26. return parseFloat(res.toFixed(12))
  27. }
  28. // 测试代码
  29. let res = calc(1.11, '*', 10)
  30. console.log(res)