JS精度计算方法

大致思路

微信图片_20211201200407.jpg

计算时把小数转整数计算,去避免 javascript 小数计算时带来的精度丢失。

1.1 * 10 转成 (11 * 100) /10

代码

const compute = (v1, type, v2) => {
  let times = 0; // 差值倍数
  console.log(v1, type, v2);
  v1 = v1.toString();
  v2 = v2.toString();
  let rightLen1 = (v1.split('.')[1] && v1.split('.')[1].length) || 0;
  let rightLen2 = (v2.split('.')[1] && v2.split('.')[1].length) || 0;
  times = rightLen1 > rightLen2 ? rightLen1 : rightLen2; // 最大长度
  console.log('times', times);
  let maxMultiple = 1;
  v1 = v1.toString().replace('.', '');
  v2 = v2.toString().replace('.', '');
  // 补零,获取倍率
  if (rightLen1 > rightLen2) {
    maxMultiple = maxMultiple + ''.padEnd(rightLen1, '0');
    v2 = v2 + ''.padEnd(times, '0');
    console.log('补零', v2);
  } else if (rightLen1 < rightLen2) {
    maxMultiple = maxMultiple + ''.padEnd(rightLen2, '0');
    v1 = v1 + ''.padEnd(times, '0');
    console.log('补零', v1);
  } else {
    maxMultiple = maxMultiple + ''.padEnd(rightLen2, '0');
  }
  console.log('maxMultiple', maxMultiple);
  // 转成number类型
  v1 = +v1;
  v2 = +v2;
  switch (type) {
    case '-':
      return (v1 - v2) / maxMultiple;
    case '+':
      return (v1 + v2) / maxMultiple;
    case '*':
      return (v1 * v2) / maxMultiple / maxMultiple;
    case '/':
      return v1 / v2;
    default:
      throw Error('运算符错误 请输入+-*/');
      break;
  }
};
let res = compute(34.35, 34.31, '-');
console.log(res);
// 加法例子 0.1+0.2
// 减法例子 34.35-34.31
// 乘法例子 1.11*10

复制代码

大致代码思路如上,可以复制代码到本地尝试或优化一下。

猜你喜欢

转载自juejin.im/post/7036701625112592392
今日推荐