背景說明
前端精度問題是很普遍的問題畔况,怎么解決呢?
解決方案
安裝 npm install decimal.js
封裝成工具
// utils.decimal.js
import Decimal from 'decimal.js'
// 加
Decimal.add = function add(x, y) {
return new this(x).plus(y).toString()
}
// 減
Decimal.sub = function sub(x, y) {
return new this(x).sub(y).toString()
}
// 乘
Decimal.mul = function (x, y) {
return new this(x).mul(y).toString()
}
// 除
Decimal.div = function div(x, y) {
return new this(x).div(y).toString()
}
Decimal.toFixed = function div(x, y) {
return new Decimal(x).toFixed(y).toString()
}
export default Decimal
使用方法
import Decimal from './utils.decimal.js'
const total = Decimal.add(num1, num2)
總結(jié)一下
這個(gè)插件很小 但可以解決前端精度問題慧库,很不錯(cuò)跷跪,記錄下來,供大家使用啦~~~