Decimal 解决前端数值计算的精度问题

1、js有精度问题, 对于一些金额的计算就总是与偶莫名其妙的问题
2、decimal.js是使用的二进制来计算的, 所以能解决js的精度问题

import { Decimal } from 'decimal.js'
//加
export function add(a, b) {
  const av = new Decimal(a)
  const bv = new Decimal(b)
  return av.plus(bv)
}
//减
export function sub(a, b) {
  const av = new Decimal(a)
  const bv = new Decimal(b)
  return av.minus(bv)
}
//乘
export function mul(a, b) {
  const av = new Decimal(a)
  const bv = new Decimal(b)
  return av.times(bv)
}
// 除
export function div(a, b) {
  const av = new Decimal(a)
  const bv = new Decimal(b)
  const cv = av.dividedBy(bv)
  if (!cv.isFinite()) {
    return new Decimal(0)
  }
  return cv
}

你可能感兴趣的:(Decimal 解决前端数值计算的精度问题)