General train of thought

To avoid the accuracy loss caused by javascript decimal calculation, convert decimals to whole numbers.

For example, 1.1 * 10 becomes (11 * 100) /10

code

const compute = (v1, type, v2) = > {
  let times = 0; // Multiple of difference
  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; // Maximum length
  console.log('times', times);
  let maxMultiple = 1;
  v1 = v1.toString().replace('. '.' ');
  v2 = v2.toString().replace('. '.' ');
  // get the multiplier
  if (rightLen1 > rightLen2) {
    maxMultiple = maxMultiple + ' '.padEnd(rightLen1, '0');
    v2 = v2 + ' '.padEnd(times, '0');
    console.log('zero padding', v2);
  } else if (rightLen1 < rightLen2) {
    maxMultiple = maxMultiple + ' '.padEnd(rightLen2, '0');
    v1 = v1 + ' '.padEnd(times, '0');
    console.log('zero padding', v1);
  } else {
    maxMultiple = maxMultiple + ' '.padEnd(rightLen2, '0');
  }
  console.log('maxMultiple', maxMultiple);
  // Type number
  v1 = +v1;
  v2 = +v2;
  switch (type) {
    case The '-':
      return (v1 - v2) / maxMultiple;
    case '+':
      return (v1 + v2) / maxMultiple;
    case The '*':
      return (v1 * v2) / maxMultiple / maxMultiple;
    case '/':
      return v1 / v2;
    default:
      throw Error('Operator error please enter +-*/');
      break; }};let res = compute(34.35.34.31.The '-');
console.log(res);
// Add example 0.1+0.2
// Subtraction example 34.35-34.31
// Multiply 1.11*10

Copy the code

As above, you can copy the code locally to try or optimize it.