JavaScript精度缺失函数

一般情况如果我们对加法,减法,乘法,触发进行运算,都会由于二进制的原因,出现精度缺失的问题,这个时候就需要进行整数型运算来排除问题。

0.2 + 0.1
0.30000000000000004

0.3 - 0.1
0.19999999999999998

0.4 * 0.1
0.04000000000000001

0.22 / 0.1
2.1999999999999997


这里函数均由个人所写,如有问题,请及时联系。


1.加法精度函数

let plusDiv = (num1, num2) => {
      let t1, t2;
      try {
        t1 = num1.toString().split('.')[1].length
      } catch (e) {
        t1 = 0
      }
      try {
        t2 = num2.toString().split('.')[1].length
      } catch (e) {
        t2 = 0
      }
      return (num1 * Math.pow(10, Math.max(t1,t2)) + num2 * Math.pow(10, Math.max(t1,t2))) / Math.pow(10, Math.max(t1,t2))
}

console.log(plusDiv(0.2,0.1))

// 0.3


2.减法精度函数

let subDiv = (num1, num2) => {
      let t1, t2;
      try {
        t1 = num1.toString().split('.')[1].length
      } catch (e) {
        t1 = 0
      }
      try {
        t2 = num2.toString().split('.')[1].length
      } catch (e) {
        t2 = 0
      }
      return (num1 * Math.pow(10, Math.max(t1,t2)) - num2 * Math.pow(10, Math.max(t1,t2))) / Math.pow(10, Math.max(t1,t2))
}

console.log(subDiv(0.3,0.1))

// 0.2


3.乘法精度函数

let multDiv = (num1, num2) => {
      let t1, t2, r1, r2
      try {
        t1 = num1.toString().split('.')[1].length
      } catch (e) {
        t1 = 0
      }
      try {
        t2 = num2.toString().split('.')[1].length
      } catch (e) {
        t2 = 0
      }
      r1 = Number(num1.toString().replace('.', ''))
      r2 = Number(num2.toString().replace('.', ''))
      // console.log(t1,t2,r1,r2,(r2 * Math.pow(10, t1 - t2)),Math.pow(10, t1 - t2))
      return r1 * r2 * (Math.pow(10,  - t1 - t2))
}
console.log(multDiv(0.4,0.1))

// 0.04


4.除法精度函数

let accDiv = (num1, num2) => {
      let t1, t2, r1, r2
      try {
        t1 = num1.toString().split('.')[1].length
      } catch (e) {
        t1 = 0
      }
      try {
        t2 = num2.toString().split('.')[1].length
      } catch (e) {
        t2 = 0
      }
      r1 = Number(num1.toString().replace('.', ''))
      r2 = Number(num2.toString().replace('.', ''))
      // console.log(t1,t2,r1,r2,(r2 * Math.pow(10, t1 - t2)),Math.pow(10, t1 - t2))
      return r1 / (r2 * Math.pow(10, t1 - t2))
}
console.log(accDiv(0.22,0.1))

// 2.2