js 金额计算时数值溢出
js 计算乘算时数字溢出
-
场景项目上为了计算税率相乘,金额有小数点乘以税率后会导致部分数字溢出,为了解决数字溢出。
-
使用 bignumber.js 库:
-
安装 npm run install bignumber.js
-
使用:
- 效果图
// 引入BigNumber
const BigNumber = require("bignumber.js");
created() {
console.log("直接相乘有数字溢出问题115.75 * 0.06=" + 115.75 * 0.06);
console.log("115.75 * 0.06=" + this.getCommonNum(115.75, 0.06));
console.log("620.75 * 0.06=" + this.getCommonNum(620.75, 0.06));
console.log("4455.45 * 0.01=" + this.getCommonNum(4455.45, 0.01));
}
/**
* value 金额
* ratio 税率
* 金额税率计算如果是整数取整,小数点小于两位保留当前数字,小数点大于3为,取第三位如果大于5需要往前面一维进一,小于5保留小数点后两位即可
*/
getCommonNum(value, ratio) {
// vue js计算乘算时数字溢出
// 使用BigNumber
const largeNumber1 = new BigNumber(value);
const largeNumber2 = new BigNumber(ratio);
const result = largeNumber1.times(largeNumber2);
const num = Number(result.toString());
const numStr = result ? result.toString() : 0;
// 判断是否是整数
if (Number.isInteger(num)) {
return num;
} else {
if (numStr.includes(".")) {
const numLen = numStr.split(".")[1].length;
if (numLen <= 2) {
return num;
} else if (numLen >= 3) {
const first = numStr.split(".")[0];
const second = numStr.split(".")[1];
const twoNum = second.slice(0, 2);
const threeNum = Number(second.slice(2, 3));
if (threeNum < 5) {
const conversion = first + "." + twoNum;
return Number(conversion);
} else {
const num1 = first + "." + twoNum;
const num12 = Number(num1) + 0.01;
return Number(num12);
}
}
}
}
}
加法
-
const a = new BigNumber('0.1')
const b = new BigNumber('0.2')
const c = a.plus(b)
console.log(c.toString())
// 输出 0.3
减法
-
const a = new BigNumber('0.3')
const b = new BigNumber('0.2')
const c = a.minus(b)
console.log(c.toString())
// 输出 0.1
乘法
-
const a = new BigNumber(3)
const b = new BigNumber(2)
const c = a.times(b)
console.log(c.toString())
// 输出 6
除法
-
const a = new BigNumber(6)
const b = new BigNumber(2)
const c = a.dividedBy(b)
console.log(c.toString())
// 输出 3
取余
-
const a = new BigNumber(7)
const b = new BigNumber(3)
const c = a.modulo(b)
console.log(c.toString())
// 输出 1