安装math.js
npm install mathjs
配置mathjs
新建mathjs.js文件内容如下
let $math = require('mathjs');// 引入依赖
function operation(_func, chain, args) {
for (let i=0,len=args.length; i<len; i++) {
chain = chain[_func]($math.bignumber(args[i]))
}
return chain;
}
// 构建对象
function BigNumber(number){
this.chain=$math.chain($math.bignumber(number));
}
// 加减乘除中间操作
BigNumber.prototype.add=function(...rest){
this.chain=operation("add",this.chain,rest);
return this;
};
BigNumber.prototype.subtract=function(...rest){
this.chain=operation("subtract",this.chain,rest);
return this;
};
BigNumber.prototype.multiply=function(...rest){
this.chain=operation("multiply",this.chain,rest);
return this;
};
BigNumber.prototype.divide=function(...rest){
this.chain=operation("divide",this.chain,rest);
return this;
};
// 输出函数
BigNumber.prototype.done=function(){
return parseFloat(this.chain.done());
};
// 四舍五入输出函数
BigNumber.prototype.toFixed=function(fractionDigits){
return parseFloat(this.chain.done()).toFixed(fractionDigits);
};
export const mathJs=number=>new BigNumber(number);
应用
import { mathJs } from '@/utils/mathjs'
let bigNumber=mathJs(10);
bigNumber.add(5);
bigNumber.subtract(1);
bigNumber.multiply(4);
bigNumber.divide(2).done();// done获取最终计算结果
bigNumber.add(1,2,3).done();// 连续相同运算,+1+2+3
bigNumber.add(1).subtract(1).multiply(1).divide(1).done();// 链式调用