浮点误差

image.png

function strip(num, precision = 12) {
  return +parseFloat(num.toPrecision(precision));
}
image.png
/**
 * 精确加法
 */
function add(num1, num2) {
  const num1Digits = (num1.toString().split('.')[1] || '').length;
  const num2Digits = (num2.toString().split('.')[1] || '').length;
  const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));
  return (num1 * baseNum + num2 * baseNum) / baseNum;
}

你可能感兴趣的:(浮点误差)