根据资料显示:是由于十进制换算成二进制,处理后,再由二进制换算成十进制时,造成的误差。
得出:所以(0.1+0.2)!=0.3
而是=0.30000000000000004的结果
解决方法:
参考:https://www.cnblogs.com/zdz8207/p/js-number-tofixed.html
加减乘除 资料https://www.cnblogs.com/xiaoxinzi/p/8482836.html
//运算方法,避免小数计算误差
acc: function(arg1, arg2, type) {
var m = 0,
s1 = arg1.toString(),
s2 = arg2.toString();
switch (type) {
//乘法
case "Mul":
try {
m += s1.split(".")[1].length
} catch (e) {}
try {
m += s2.split(".")[1].length
} catch (e) {}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
break;
//除法
case "Div":
//加法
case "Add":
//减法
case "Sub":
var r1, r2, m;
try {
r1 = arg1.toString().split(".")[1].length
} catch (e) {
r1 = 0
}
try {
r2 = arg2.toString().split(".")[1].length
} catch (e) {
r2 = 0
}
m = Math.pow(10, Math.max(r1, r2))
if (type == "Div")
return ((arg1 * m) / (arg2 * m))
if (type == "Add")
return (arg1 * m + arg2 * m) / m
if (type == "Sub")
return (arg1 * m - arg2 * m) / m
break;
}
}