常见例子
// 加法
0.1 + 0.2 = 0.30000000000000004
0.1 + 0.7 = 0.7999999999999999
0.2 + 0.4 = 0.6000000000000001
// 减法
0.3 - 0.2 = 0.09999999999999998
1.5 - 1.2 = 0.30000000000000004
// 乘法
0.8 * 3 = 2.4000000000000004
19.9 * 100 = 1989.9999999999998
// 除法
0.3 / 0.1 = 2.9999999999999996
0.69 / 10 = 0.06899999999999999
// 比较
0.1 + 0.2 === 0.3 // false
(0.3 - 0.2) === (0.2 - 0.1) // false
解决方法
-
加
Vue.prototype.NumberAdd = function(arg1, arg2) { var r1, r2, m, n; 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)) n = (r1 >= r2) ? r1 : r2; return ((arg1 * m + arg2 * m) / m).toFixed(n); }
-
减
Vue.prototype.NumberSub = function(arg1, arg2) { var re1, re2, m, n; try { re1 = arg1.toString().split(".")[1].length; } catch (e) { re1 = 0; } try { re2 = arg2.toString().split(".")[1].length; } catch (e) { re2 = 0; } m = Math.pow(10, Math.max(re1, re2)); n = (re1 >= re2) ? re1 : re2; return ((arg1 * m - arg2 * m) / m).toFixed(n); }
-
乘
Vue.prototype.NumberMul = function(arg1, arg2) { var m = 0; var s1 = arg1.toString(); var 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); }
-
除
原文地址// 除数,被除数, 保留的小数点后的位数 Vue.prototype.NumberDiv = function (arg1,arg2,digit){ var 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(".","")) //获取小数点后的计算值 var result= ((r1/r2)*Math.pow(10,t2-t1)).toString() var result2=result.split(".")[1]; result2=result2.substring(0,digit>result2.length?result2.length:digit); return Number(result.split(".")[0]+"."+result2); }