math.js解决js计算精度问题

文章介绍了如何在Node.js项目中安装并使用math.js库,封装了一个可接受字符串输入并处理大数的数学操作函数,支持加、减、乘、除,同时处理小数位数

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,安装 "math.js" 库:

npm install mathjs

导入

const math = require('mathjs');

封装方法

export function performOperation(operation, num1, num2, decimalPlaces) {//类型,值1,值2,取几位小数
  const num1Value = typeof num1 === 'string' ? parseFloat(num1) : num1;//传入字符串类型进行转换
  const num2Value = typeof num2 === 'string' ? parseFloat(num2) : num2;

  let result;
  switch (operation) {
    case 'add'://加
      result = math.add(math.bignumber(num1Value), math.bignumber(num2Value));
      break;
    case 'subtract'://减
      result = math.subtract(math.bignumber(num1Value), math.bignumber(num2Value));
      break;
    case 'multiply'://乘
      result = math.multiply(math.bignumber(num1Value), math.bignumber(num2Value));
      break;
    case 'divide'://除
      if (num2Value === 0) {
        throw new Error("不允许除零");
      }
      result = math.divide(math.bignumber(num1Value), math.bignumber(num2Value));
      break;
    default:
      throw new Error("无效的操作。支持的操作有“加”、“减”、“乘”和“除”。");
  }

  return math.format(result, { notation: 'fixed', precision: decimalPlaces });
}

封装后可以放在utils文件下面,export function可以全局引用这个方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值