`

js 加减乘除精度问题

    博客分类:
  • js
阅读更多

一。加法精度修改后如下:

function add(...val) {
      let max = 0
      let count = 0
      for (let i = 0; i < val.length; i++) {
        const strVal = val[i].toString()
        const index = strVal.indexOf('.')
        let num = 0
        if (index > -1) {
          num = strVal.length - 1 - index
          max = num > max ? num : max
        }
      }
      for (let i = 0; i < val.length; i++) {
        count += Math.round(val[i] * Math.pow(10, max))
      }
      return count / Math.pow(10, max)
    }

 使用:add(0.1, 0.2, 0.3, 0.4) => 1。可以传多个参数进行相加。

 

二。减法精度修改后如下:

function sub(...val) {
      let max = 0
      let count = val[0] | 0
      for (let i = 0; i < val.length; i++) {
        const strVal = val[i].toString()
        const index = strVal.indexOf('.')
        let num = 0
        if (index > -1) {
          num = strVal.length - 1 - index
          max = num > max ? num : max
        }
      }
      for (let i = 0; i < val.length; i++) {
        count -= Math.round(val[i] * Math.pow(10, max))
      }
      return count / Math.pow(10, max)
    }

 使用:sub(1, 0.2, 0.3, 0.4) => 0.1。相当于1 - 0.2 -0.3 -0.4;可以传多个参数,使用首位减后面的所有参数。

 

三。乘法精度修改后如下:

function ride(...val) {
      const strVal = val[0].toString()
      const strValTwo = val[1].toString()
      const index = strVal.indexOf('.')
      const indexTwo = strValTwo.indexOf('.')
      const num = [0, 0]
      if (index > -1) {
        num[0] = strVal.length - 1 - index
      }
      if (indexTwo > -1) {
        num[1] = strValTwo.length - 1 - index
      }
      return Math.round((val[0] * Math.pow(10, num[0])) * (val[1] * Math.pow(10, num[1]))) / Math.pow(10, num[0] + num[1])
    }

 使用:ride(0.5, 0.6) => 3, 只允许传入两个参数。%计算可以这样ride(0.5, 100) => 50。

function percentage(val) {
      const strVal = val.toString()
      const index = strVal.indexOf('.')
      let num = 0
      if (index > -1) {
        num = strVal.length - 1 - index
      }
      if (num > 2) {
        return Math.round(val * Math.pow(10, num)) / Math.pow(10, num - 2)
      } else {
        return Math.round(val * 100)
      }
    }

 上面这个是专门用于计算%数的。percentage(0.05) => 5

 

四。除法精度修改后如下:

function exc(val, valTwo = 100) {
      const strVal = val.toString()
      const strValTwo = valTwo.toString()
      const index = strVal.indexOf('.')
      const indexTwo = strValTwo.indexOf('.')
      const num = [0, 0]
      if (index > -1) {
        num[0] = strVal.length - 1 - index
      }
      if (indexTwo > -1) {
        num[1] = strValTwo.length - 1 - index
      }
      return Math.round(val * Math.pow(10, num[0])) / (Math.round((valTwo * Math.pow(10, num[1]))) * Math.pow(10, num[0] - num[1]))
    }

 使用:exc(0.5, 0.2) => 2.5, 只允许传入两个参数。如果计算出现无穷数请后期根据需要修改最后代码进行取舍。

 

建议:所有的计算最后都由后端处理好,再传到前端,这样可以避免精度问题。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics