首先,安装 "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可以全局引用这个方法。