bignumber.js
下载地址:https://github.com/MikeMcl/bignumber.js/releases
为了解决精度丢失的问题
安装: npm install bignumber.js
import BigNumber from "bignumber.js"
// 相乘 参数:dec 保留小数
accFloatMul(num1, num2, dec) {
let res =new BigNumber(num1).multipliedBy(new BigNumber(num2)).toFixed(dec)
if (dec) {
const numArr = String(res).split('.')
// 获取当输入小数位数
const decimal = numArr[1] || ''
if (decimal === '0'.repeat(dec)) {
res =new BigNumber(res).toFixed(0)
}
}
return res
}
// 相加
accFloatAdd(num1, num2, dec) {
let res =new BigNumber(num1).plus(new BigNumber(num2)).toFixed(dec)
if (dec) {
const numArr = String(res).split('.')
// 获取当输入小数位数
const decimal = numArr[1] || ''
if (decimal === '0'.repeat(dec)) {
res =new BigNumber(res).toFixed(0)
}
}
return res
}
// 相减
accFloatSub(num1, num2, dec) {
let res =new BigNumber(num1).minus(new BigNumber(num2)).toFixed(dec)
if (dec) {
const numArr = String(res).split('.')
// 获取当输入小数位数
const decimal = numArr[1] || ''
if (decimal === '0'.repeat(dec)) {
res =new BigNumber(res).toFixed(0)
}
}
return res
}
// 相除
accFloatDiv(num1, num2, dec) {
let res =new BigNumber(num1).dividedBy(new BigNumber(num2)).toFixed(dec)
if (dec) {
const numArr = String(res).split('.')
// 获取当输入小数位数
const decimal = numArr[1] || ''
if (decimal === '0'.repeat(dec)) {
res =new BigNumber(res).toFixed(0)
}
}
return res
}