項目中出現金額的四則運算精度錯誤問題,引入math.js來解決,並封裝四則運算方法。
安裝: npm install mathjs
引入方式一:在main.js中, //網上查詢得來
import * as math from 'mathjs'; // 親測import math from 'mathjs';不可取,朋友指出是因爲math.js源碼導出爲模塊化導出。
Vue.prototype.$math = math; //掛在到原型
之後可以在其他頁面中 直接使用 this.$math.add(a,b)加,this.$math.subtract(a,b) 減,this.$math.multiply(a,b)乘,this.$math.divide(a,b)除。 a和b需要使用this.$math.bignumber();格式化一下數據類型。
例如: this.$math.add(this.$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);
以上引入方法,都是網上查資料學習得來,只是總結歸納一下,也希望能幫到其他人,謝謝。
封裝方法也是自己學習方法的封裝和使用,並練習一下而已。