js 小数精确计算 (mathjs / decimal.js)

mathjs

import { all, create } from "mathjs";

let mathjs = create(all, {
  precision: 14,
  number: "BigNumber",
});

/**加法 */
export function jia(left: any, right: any) {
  return mathjs.floor(Number(mathjs.add(mathjs.bignumber(left), mathjs.bignumber(right))), 2);
}
/**减法 */
export function jian(left: any, right: any) {
  return mathjs.floor(Number(mathjs.subtract(mathjs.bignumber(left), mathjs.bignumber(right))), 2);
}

/** 乘法 */
export function cheng(left: any, right: any) {
  return mathjs.floor(Number(mathjs.multiply(mathjs.bignumber(left), mathjs.bignumber(right))), 2);
}
/** 除法 */
export function chu(left: any, right: any) {
  return mathjs.floor(Number(mathjs.divide(mathjs.bignumber(left), mathjs.bignumber(right))), 2);
}

decimal.js

mathjs 底层是 decimal.js

import { Decimal } from "decimal.js";

/**加法 */
export function jia(left: Decimal.Value, right: Decimal.Value) {
  return Number(Decimal.add(left, right).toFixed(2, Decimal.ROUND_DOWN));
}
/**减法 */
export function jian(left: Decimal.Value, right: Decimal.Value) {
  return Number(Decimal.sub(left, right).toFixed(2, Decimal.ROUND_DOWN));
}

/** 乘法 */
export function cheng(left: Decimal.Value, right: Decimal.Value) {
  return Number(Decimal.mul(left, right).toFixed(2, Decimal.ROUND_DOWN));
}
/** 除法 */
export function chu(left: Decimal.Value, right: Decimal.Value) {
  return Number(Decimal.div(left, right).toFixed(2, Decimal.ROUND_DOWN));
}

其他

// 保留最后两位
export function keepTwoDecimalWithReg(num: number) {
  return Number(num.toString().match(/^d+(?:.d{0,2})?/));
}