1. 程式人生 > >js中的小數計算精度問題,修正計算精度

js中的小數計算精度問題,修正計算精度

js 的精度問題這個網上比較多,進行加減乘除運算也難免,常見的比如:

1)在控制檯 輸入:1.1+0.3 運算結果是:1.4000000000000001,根本原因也就是二進位制和十進位制轉換的問題,具體源由參考網上相關文章,有一種解決辦法:兩個數分別剩10的N次方最後再除10的N次方,比如:(1.1*10+0.3*10)/10  ,貌似沒有什麼問題,但是還是有問題的,只是問題比較隱蔽


2)【容易忽略的精度問題】 比如:

       var  num=35.41;

        num*100結果是什麼?3541?

        在偵錯程式和控制檯中可以看到,這個值為【3540.9999999999994】,如此看來小數乘10的倍數是存在問題的,

        所以如果頁面存在一個需求: 頁面小數運算結果為【0】的時候做點什麼的話。。。那它就永遠也不相等,其結果是一個很接近0的數比如:-6.25e-15;

        所以,把想把小數轉整數不是麼簡單的乘個10的N次方,

       類似的值還有 【20.06】  20.06*100 =?     2005.9999999999998

       解決方法就是,【20.06】拆成,2000 和6 然後分別和100相乘相加再除100  原理是這樣,做起來的話,貼程式碼

// -
// -
minus:function(n,m){
    n=typeof n =="string"?n:this.numToString(n);
    m=typeof m =="string"?m:this.numToString(m);
    var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0],
        S= m.indexOf
(".")!=-1?this.handleNum(m):[m,0,0], l1=F[2], l2=S[2], L=l1>l2?l1:l2, T=Math.pow(10,L); return (F[0]*T+F[1]*T/Math.pow(10,l1)-S[0]*T-S[1]*T/Math.pow(10,l2))/T }, // * multiply:function(n,m){ n=typeof n =="string"?n:this.numToString(n); m=typeof m =="string"?m:this.numToString(m); var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0], S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0], l1=F[2], l2=S[2], L=l1>l2?l1:l2, T=Math.pow(10,L); return ((F[0]*T+F[1]*T/Math.pow(10,l1))*(S[0]*T+S[1]*T/Math.pow(10,l2)))/T/T }, // / division:function(n,m){ n=typeof n =="string"?n:this.numToString(n); m=typeof m =="string"?m:this.numToString(m); var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0], S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0], l1=F[2], l2=S[2], L=l1>l2?l1:l2, T=Math.pow(10,L); return ((F[0]*T+F[1]*T/Math.pow(10,l1))/(S[0]*T+S[1]*T/Math.pow(10,l2))) }, numToString:function(tempArray){ if(Object.prototype.toString.call(tempArray) == "[object Array]"){ var temp=tempArray.slice(); for(var i,l=temp.length;i<l;i++){ temp[i]=typeof temp[i] == "number"?temp[i].toString():temp[i]; } return temp; } if(typeof tempArray=="number"){ return tempArray.toString(); } return [] }, plus:function(n,m){ n=typeof n =="string"?n:this.numToString(n); m=typeof m =="string"?m:this.numToString(m); var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0], S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0], l1=F[2], l2=S[2], L=l1>l2?l1:l2, T=Math.pow(10,L); return (F[0]*T+F[1]*T/Math.pow(10,l1)+S[0]*T+S[1]*T/Math.pow(10,l2))/T }, handleNum:function(n){ n=typeof n !=="string"?n+"":n; var temp= n.split("."); temp.push(temp[1].length); return temp },