众所周知的 JS 二进制精度问题,特别是乘除法精确小数位计算的时候尤其容易出现。原理看下面链接详细说明,这里我们采用 JS 原生方法处理这个问题,不过也有专门的类库提供选择。
用法:演示加法,其他都一样
function jiafa(){
var a = 10;
var b = 20 ;
var c = add(a,b);
}
function add(arg1, arg2) {
arg1 = arg1.toString(), arg2 = arg2.toString();
var arg1Arr = arg1.split("."), arg2Arr = arg2.split("."), d1 = arg1Arr.length == 2 ? arg1Arr[1]
: "", d2 = arg2Arr.length == 2 ? arg2Arr[1] : "";
var maxLen = Math.max(d1.length, d2.length);
var m = Math.pow(10, maxLen);
var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen));
var d = arguments[2];
return typeof d === "number" ? Number((result).toFixed(d)) : result;
}
function sub(arg1, arg2) {
return add(arg1, -Number(arg2), arguments[2]);
}
function mul(arg1, arg2) {
var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
m = (r1.split(".")[1] ? r1.split(".")[1].length : 0)
+ (r2.split(".")[1] ? r2.split(".")[1].length : 0);
resultVal = Number(r1.replace(".", "")) * Number(r2.replace(".", ""))
/ Math.pow(10, m);
return typeof d !== "number" ? Number(resultVal) : Number(resultVal
.toFixed(parseInt(d)));
}
function div(arg1, arg2) {
var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
m = (r2.split(".")[1] ? r2.split(".")[1].length : 0)
- (r1.split(".")[1] ? r1.split(".")[1].length : 0);
resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", ""))
* Math.pow(10, m);
return typeof d !== "number" ? Number(resultVal) : Number(resultVal
.toFixed(parseInt(d)));
}