js小數計算丟失精度問題解決方法

2021-09-26 13:29:36 字數 1576 閱讀 6628

1 小數計算bug: 

console.log( 1 - 0.8 ); //輸出 0.19999999999999996

console.log( 6 * 0.7 ); //輸出 4.199999999999999

console.log( 0.1 + 0.2 ); //輸出 0.30000000000000004

console.log( 0.1 + 0.7 ); //輸出 0.7999999999999999

console.log( 1.2 / 0.2 ); //輸出 5.999999999999999

通過上面舉出的例子可以看到,原生的js運算結果不一定準確,會丟失精度。

2 產生原因:

計算機能讀懂的是二進位制,進行運算的時候,實際上是把數字轉換為了二進位制進行的 這個過程 丟失了精度

3 通常的解決方法 計算之前*10的n次方 計算之後在除10的n次方

例如: console.log(1-0.8); 變為 console.log((1 * 10 - 0.8 * 10) / 10);

但是: 9033742.2*100 ----->903374219 (還是有一些特殊情況 不能直接*10的n次方)

4 根據上述原理 做一下修改小數點擷取轉數字在計算,可以封裝一些方法出來解決此類問題。如下所示(math.pow(x, y);表示求x的y次方):

function floatadd(arg1,arg2)catch(e)

trycatch(e)

m=math.pow(10,math.max(r1,r2));

return (arg1*m+arg2*m)/m;

}

//減

function floatsub(arg1,arg2)catch(e)

trycatch(e)

m=math.pow(10,math.max(r1,r2));

//動態控制精度長度

n=(r1>=r2)?r1:r2;

return ((arg1*m-arg2*m)/m).tofixed(n);

}

//乘

function floatmul(arg1,arg2) catch(e){}

trycatch(e){}

return number(s1.replace(".","")) * number(s2.replace(".","")) /math.pow(10,m);

}

//除

function floatdiv(arg1,arg2)catch(e){}

trycatch(e){}

r1=number(arg1.tostring().replace(".",""));

r2=number(arg2.tostring().replace(".",""));

return (r1/r2)*math.pow(10,t2-t1);

}

js計算小數精度問題

js進行部分小數運算時,會出現精度問題。解決思路是,把小數同時擴大為10的x冪,返回計算完畢後,再縮小為10的x冪。在math方法上新增加減乘除方法。let extentfns add sub mul div 運算函式 function ufunc type,arg catch e decimald...

PHP Session丟失問題解決

正常設定session,但是在某些windows伺服器始終有session丟失情況 session1.php 正常設定session,但是在某些windows伺服器造成session丟失 session start session test helloworld header location se...

mysql密碼丟失問題解決

1 結束mysqld.exe程序,停止mysql服務 停止mysql服務 net stop mysql2 將當前目錄切換到mysql的bin目錄 cd mysql mysql5.6.17 bin cd c wamp bin mysql mysql5.6.17 bin3 開啟乙個cmd視窗,執行命令跳...