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

发布时间:2024年01月21日

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
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。