如何优雅解决 js小数点计算错误问题(三个函数告诉你解决办法)

策略就是把小数值变成整数进行操作加减乘除
github — L6zt

// 获取最大补位长度
const findMinRadixPoint = (numberList) => {
  let maxLg = 0;
  numberList.forEach(num => {
    let numStr = num.toString();
    let numSplit = numStr.split('.');
    let bitLg =  (numSplit[1] || '').length;
    (bitLg > maxLg) && (maxLg = bitLg)
  });
  return maxLg
};

/*数字补位*/
const numberCoverPosition = (number, length) => {
  let numberStr = String(number);
  let lg = numberStr.length;
  let idx = numberStr.indexOf('.');
  if (idx === -1) {
    return number * Math.pow(10, length);
  } else {
    let addW = length - (lg - 1 - idx);
    let oLoop = '';
    while (addW) {
      oLoop += '0';
      addW--;
    }
    return Number(numberStr.replace(/(\d+?)\.(\d+?)/, `$1$2${oLoop}`))
  }
};
/*数字减位*/
const NumberDigitAbsorption = (number, length) => {
  let numberStr = String(number);
  let lg = numberStr.length;
  
  if (lg > length) {
    numberStr = numberStr.substr(0, lg - length) + '.' + numberStr.substr(lg - length);
  } else {
    let leftW = length - lg;
    let oLoop = '';
    while (leftW) {
      oLoop += '0';
      leftW--;
    }
    numberStr = '0.' + oLoop + numberStr
  }
  return numberStr
};
    原文作者:前端
    原文地址: https://segmentfault.com/a/1190000018592152
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞