解决js中小数相加损失精度的问题

function addFloatNumber() {
  const args = arguments;
  const len = args.length;
  let initFloatLen = 0;
  let sum = 0;

  let strItem = '';
  let tmpLen = 0;
  for (key in args) {
    strItem = args[key].toString();
    if (strItem.indexOf('.') != -1) {
      tmpLen = strItem.split('.')[1].length;
      initFloatLen = initFloatLen < tmpLen ? tmpLen : initFloatLen;
    }
  } // for
  const m = Math.pow(10, initFloatLen);
  for (key in args) {
    sum += args[key] * m;
  }
  return sum / m;
}


你可能感兴趣的:(解决js中小数相加损失精度的问题)