toFixed精度丢失问题

bug说明:
toFixed精度丢失问题_第1张图片

10.3950 * 3935.00 用toFixed(2) 得到的是40904.32 实际应该是40904.33

解决的方法:
第一种:

在main.js中直接复制下面代码即可

Number.prototype.toFixed = function (n) {
  n = n || 0
  let resNum = Math.round((this * Math.pow(10, n + 1)) / 10) / Math.pow(10, n)
  let resNumString = resNum.toString()
  let dotIndex = resNumString.indexOf('.')
  if (dotIndex < 0 && n > 0) {
    dotIndex = resNumString.length
    resNumString += '.'
  }
  while (resNumString.length <= dotIndex + n) {
    resNumString += '0'
  }
  return resNumString
}

第二种:
在main.js中直接复制下面代码即可

// js
if (!Number.prototype._toFixed) {
  // eslint-disable-next-line no-extend-native
  Number.prototype._toFixed = Number.prototype.toFixed
}
// eslint-disable-next-line no-extend-native
Number.prototype.toFixed = function (d) {
  var s = this + "";
  if (!d) d = 0;
  if (s.indexOf(".") === -1) s += ".";
  s += new Array(d + 1).join("0");
  if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
    let s = "0" + RegExp.$2; var pm = RegExp.$1; var a = RegExp.$3.length; var b = true;
    if (a === d + 2) {
      a = s.match(/\d/g);
      if (parseInt(a[a.length - 1]) > 4) {
        for (var i = a.length - 2; i >= 0; i--) {
          a[i] = parseInt(a[i]) + 1;
          if (a[i] === 10) {
            a[i] = 0;
            b = i !== 1;
          } else break;
        }
      }
      s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");
    }
    if (b) s = s.substr(1);
    return (pm + s).replace(/\.$/, "");
  }
  return this + "";
};

你可能感兴趣的:(前端,javascript)