JS里精度缺失问题,比如 0.1 + 0.2 = 0.300000000000000004,这就是典型的精度缺失。但是如果使用保留小数位,就很有可能会造成数据不准确。所以换个思路,把小数变成整数再去做运算。
let Utils = {argAdd: function(arg1, arg2) {// 加法函数var _this = this,r1 = 0,r2 = 0,m = 0;try {r1 = arg1.toString().split(".")[1].length} catch(e) {}try {r2 = arg2.toString().split(".")[1].length} catch(e) {}m = Math.pow(10, Math.max(r1, r2))return _this.argDiv((_this.argMul(arg1, m) + _this.argMul(arg2, m)), m)},argSubtr: function(arg1, arg2) {// 减法函数var _this = this,r1 = 0,r2 = 0,m = 0;try {r1 = arg1.toString().split(".")[1].length} catch(e) {}try {r2 = arg2.toString().split(".")[1].length} catch(e) {}m = Math.pow(10, Math.max(r1, r2));return _this.argDiv((_this.argMul(arg1, m) - _this.argMul(arg2, m)), m)},argMul: function(arg1, arg2) {// 乘法函数var _this = this,m = 0,s1 = arg1.toString(),s2 = arg2.toString();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)},argDiv: function(arg1, arg2) {// 除法函数var _this = this,t1 = 0,t2 = 0,r1, r2;try {t1 = arg1.toString().split(".")[1].length} catch(e) {}try {t2 = arg2.toString().split(".")[1].length} catch(e) {}r1 = Number(arg1.toString().replace(".", ""))r2 = Number(arg2.toString().replace(".", ""))return _this.argMul((r1 / r2), Math.pow(10, t2 - t1));}
}