js calculation component decimal calculation distortion problem solving (mathjs)

There will be problems with decimal calculations: for example, the calculation result should be 2.3, but the console.log shows 2.2999999999998. Mathjs like this
is a good solution.
Code environment VUE3

1. Download dependencies

npm install mathjs

2. Introduction and application (it is best to create a math.js secondary package under utils)

import * as $math from 'mathjs';

export const math = {
    
    
  // ti + t2
  addTwo (t1, t2) {
    
    
    return parseFloat($math.format($math.chain(t1 || 0).add($math.bignumber(t2 || 0)).done()));
  },
  // ti - t2
  subtractTwo (t1, t2) {
    
    
    return parseFloat($math.format($math.chain(t1 || 0).subtract($math.bignumber(t2 || 0)).done()));
  },
  // ti X t2
  multiplyTwo (t1, t2) {
    
    
    return parseFloat($math.format($math.chain(t1 || 0).multiply($math.bignumber(t2 || 0)).done()));
  }
  // ti / t2
  divideTwo (t1, t2) {
    
    
    return parseFloat($math.format($math.chain(t1 || 0).divide($math.bignumber(t2 || 0)).done()));
  }
};

3. use

import {
    
     math } from '@/utils/math';

// 例如 调用加法 a + b
math.addTwo(a, b);
// 例如 调用减法 a - b
math.subtractTwo(a, b);
// 例如 调用乘法 a X b
math.multiplyTwo(a, b);
// 例如 调用除法 a / b
math.divideTwo(a, b);

Guess you like

Origin blog.csdn.net/weixin_34403976/article/details/127430057