javascript進行浮點運算會有尾差,比如算個0.1+0.7試試,得到的不是0.8 。這個問題可以使用math.js解決。
Math.js是一款開源的JavaScript和Node.js數學庫,用於處理數字、大數、復數、單位和矩陣。官網: http://mathjs.org/
<html> <head> <script src="math.js"></script> <script type="text/javascript"> function fn_click(p){ var a , b; a=0.7; b=0.1; if(p==1){ alert(a+b); }else if(p==2){ alert(eval("a+b")); }else if(p==3){ math.config({ number: 'BigNumber' }); var result = math.parser().eval(a + "+" + b) alert(result); } } </script> </head> <body> <input type="button" value="0.7+0.1" onclick="fn_click(1);" /> <input type="button" value="eval(0.7+0.1)" onclick="fn_click(2);" /> <input type="button" value="mathjs(0.7+0.1)" onclick="fn_click(3);" /> </body> </html>
上面分別用3種方法計算0.7+0.1,可以看到使用math.parser().eval()計算得到了准確的結果0.8