Mathjs库(JS8)

Math.js库

官网:https://mathjs.org/

项目中出现金额的四则运算精度错误问题,引入math.js来解决,并封装四则运算方法。

安装: npm install mathjs

引入方式一:在main.js中, //网上查询得来

import * as math from ‘mathjs’; // 亲测import math from ‘mathjs’;不可取,朋友指出是因为math.js源码导出为模块化导出。

Vue.prototype.$math = math; //挂在到原型

之后可以在其他页面中 直接使用 this. m a t h . a d d ( a , b ) 加 , t h i s . math.add(a,b)加,this. math.adda,bthis.math.subtract(a,b) 减,this. m a t h . m u l t i p l y ( a , b ) 乘 , t h i s . math.multiply(a,b)乘,this. math.multiplya,bthis.math.divide(a,b)除。 a和b需要使用this.$math.bignumber();格式化一下数据类型。

例如: this. m a t h . a d d ( t h i s . math.add(this. math.addthis.math.bignumber(a),this.$math.bignumber(b)); 太繁琐了,所以方便起见将其封装一下子。

引入方法二:在main.js中, //网上查询得来

const { create, all } = require(‘mathjs’)

const config = {

number:‘BigNumber’,

precision:20 //精度 20。 precision: BigNumbers的最大有效位数。

}

const math = create(all,config);

Vue.prototype.$math = math;

使用同上。

引入方法三:在使用的页面中

let math = require(‘mathjs’); //网上查询得来

math.add(math.bignumber(a),math.bignumber(b));

math.subtract(math.bignumber(a),math.bignumber(b));

math.multiply(math.bignumber(a),math.bignumber(b));

math.divide(math.bignumber(a),math.bignumber(b));

封装方法一:先在arithmetic.js(名称随意),中引入math.js(参考上面引入方法,并不用挂载到原型上)

let arithmetic = {

//加法

add(a,b){

    return math.add(math.bignumber(a), math.bignumber(b));

},

//减法

subtract(a,b){

    return math.subtract(math.bignumber(a), math.bignumber(b));

},

// 乘法

multiply(a,b){

    return math.subtract(math.bignumber(a), math.bignumber(b));

},

// 除法

divide(a,b){

    return math.subtract(math.bignumber(a), math.bignumber(b));

}

}

export default arithmetic;

使用:import arithmetic from “…/utils/arithmetic”;

arithmetic.add(a,b);

arithmetic.subtract(a,b);

arithmetic.multiply(a,b);

arithmetic.divide(a,b); //看起来简洁方便很多。

封装方法二:引入math.js ,在arithmetic.js中

//加法

function add(a,b){

return math.add(math.bignumber(a), math.bignumber(b));

};

//减法

function subtract(a,b){

return math.subtract(math.bignumber(a), math.bignumber(b));

};

// 乘法

function multiply(a,b){

return math.subtract(math.bignumber(a), math.bignumber(b));

};

// 除法

function divide(a,b){

return math.subtract(math.bignumber(a), math.bignumber(b));

};

module.exports = {

add,

subtract,

multiply,

divide

}; //模块导出

使用:import {add,subtract,multiply,divide} from “…/utils/arithmetic” //按需引入 ,使用哪个方法引入哪个。
add(a,b);
subtract(a,b);
multiply(a,b);
divide(a,b);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值