背景说明
前端精度问题是很普遍的问题,怎么解决呢?
解决方案
安装 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)
总结一下
这个插件很小 但可以解决前端精度问题,很不错,记录下来,供大家使用啦~~~