自学内容网 自学内容网

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})?/));
}

原文地址:https://blog.csdn.net/qq_37214567/article/details/135723212

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!