美文网首页Vue.js
2019-12-06 js数字计算精度误差问题,解决办法!!!

2019-12-06 js数字计算精度误差问题,解决办法!!!

作者: deadcalm | 来源:发表于2019-12-06 15:18 被阅读0次

    需要拿走,有问题请提出,不谢 🤣🤣🤣

    Number.prototype.add = function(num) {
      let str = this.toString().split('.')
      let str1 = num.toString().split('.')
    
      let that = 0
      let thatNum = 0
    
      if (str.length > 1) {
        that = str[1].length
      }
    
      if (str1.length > 1) {
        thatNum = str1[1].length
      }
    
      let len = Math.pow(10, Math.max(that, thatNum))
    
      return (this * len + num * len) / len
    }
    
    Number.prototype.sub = function(num) {
      let str = this.toString().split('.')
      let str1 = num.toString().split('.')
    
      let len = 0
      let lenNum = 0
    
      if (str.length > 1) {
        len = str[1].length
      }
    
      if (str1.length > 1) {
        lenNum = str1[1].length
      }
    
      let pow = Math.pow(10, Math.max(len, lenNum))
    
      return (this * len - num * pow) / pow
    }
    
    Number.prototype.sub = function(num) {
      let str = this.toString().split('.')
      let str1 = num.toString().split('.')
    
      let len = 0
      let lenNum = 0
    
      if (str.length > 1) {
        len = str[1].length
      }
    
      if (str1.length > 1) {
        lenNum = str1[1].length
      }
    
      let pow = Math.pow(10, Math.max(len, lenNum))
    
      return (this * len - num * pow) / pow
    }
    
    Number.prototype.multiply = function(num) {
      let strThis = this.toString()
      let strNum = num.toString()
      let str = strThis.split('.')
      let str1 = strNum.split('.')
      let len = 0
    
      if (str.length > 1) {
        len += str[1].length
      }
    
      if (str1.length > 1) {
        len += str1[1].length
      }
      
      let pow = Math.pow(10, len)
    
      return (strThis.replace('.', '') * strNum.replace('.', '')) / pow
    }
    
    Number.prototype.divide = function(num) {
      let strThis = this.toString()
      let strNum = num.toString()
      let str = strThis.split('.')
      let len = strNum.length
    
      if (str.length > 1) {
        len += str[1].length
      }
    
      let pow = Math.pow(10, len)
    
      return this * pow / num / pow
    }
    
    

    相关文章

      网友评论

        本文标题:2019-12-06 js数字计算精度误差问题,解决办法!!!

        本文链接:https://www.haomeiwen.com/subject/hugsgctx.html