js精度计算问题

  // 匹配小数点后有几位
  const countDecimal = (num: any) => {
    const regex = /\.(\d+)/;
    const match = regex.exec(num.toString());
    return match ? match[1].length : 0;
  };

  // 加减计算
  const getNum = (n1: number, n2: number, add = true) => {
    const multiple = Math.max(countDecimal(n1), countDecimal(n2));
    const m1 = Math.pow(10, multiple);
    const _n1 = Math.floor(n1 * m1);
    const _n2 = Math.floor(n2 * m1);
    return add ? (_n1 + _n2) / m1 : (_n1 - _n2) / m1;
  };

你可能感兴趣的:(javascript,开发语言,前端)