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 = Number(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);
}
} else {
return num;
}
}
}
}
标签:numStr,const,0.06,Number,数值,js,溢出
From: https://www.cnblogs.com/DCL1314/p/18176652