Vue.js

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

2019-12-06  本文已影响0人  deadcalm

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

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
}

上一篇 下一篇

猜你喜欢

热点阅读