[問題] Javascript 詭異的計算問題

作者: anawak (...)   2013-12-08 06:37:02
剛發現表單數值有一個詭異的數字: 0.35000000000000003
後來發現竟然是 350 * 0.001 算出來的結果。
多試了幾組數字:
340*0.001=0.34
341*0.001=0.341
342*0.001=0.342
343*0.001=0.343
344*0.001=0.34400000000000003
345*0.001=0.34500000000000003
346*0.001=0.34600000000000003
347*0.001=0.34700000000000003
348*0.001=0.34800000000000003
349*0.001=0.34900000000000003
350*0.001=0.35000000000000003
351*0.001=0.35100000000000003
352*0.001=0.352
353*0.001=0.353
354*0.001=0.354
355*0.001=0.355
為什麼 344 到 351 之間的數字,乘上 0.001 會跑出那樣的結果?
跟二進位近似值什麼的有關嗎?
IE, Firefox, Chrome 都一樣。
有沒有什麼規律?該怎麼去掉小數點尾巴那個 3 ?
程式碼
<script>
cal=340*0.001; document.write('340*0.001='+cal+'<BR>');
cal=341*0.001; document.write('341*0.001='+cal+'<BR>');
cal=342*0.001; document.write('342*0.001='+cal+'<BR>');
cal=343*0.001; document.write('343*0.001='+cal+'<BR>');
cal=344*0.001; document.write('344*0.001='+cal+'<BR>');
cal=345*0.001; document.write('345*0.001='+cal+'<BR>');
cal=346*0.001; document.write('346*0.001='+cal+'<BR>');
cal=347*0.001; document.write('347*0.001='+cal+'<BR>');
cal=348*0.001; document.write('348*0.001='+cal+'<BR>');
cal=349*0.001; document.write('349*0.001='+cal+'<BR>');
cal=351*0.001; document.write('351*0.001='+cal+'<BR>');
cal=352*0.001; document.write('352*0.001='+cal+'<BR>');
cal=353*0.001; document.write('353*0.001='+cal+'<BR>');
cal=354*0.001; document.write('354*0.001='+cal+'<BR>');
cal=355*0.001; document.write('355*0.001='+cal+'<BR>');
</script>
作者: juicyroach (發呆過生活)   2013-02-08 10:36:00
個人猜測是rounding error
作者: CaptainH (Cannon)   2013-02-08 11:25:00
浮點數會有精度問題 所有語言都一樣
作者: mrbigmouth (大嘴先生)   2013-02-08 12:26:00
運算前先化為整數即可
作者: danny8376 (釣到一隻猴子@_@)   2013-02-08 12:39:00
樓上... 這邊就是小數運算 化整數要算啥啊...總之上面都有推到了 可以的話你改 /1000 就沒這問題了
作者: TonyQ (自立而後立人。)   2013-02-08 13:37:00
這問題標準解之一是轉整數運算沒錯。只是要運算的話,抓一下你精度要到小數幾位處理就好。
作者: dlikeayu (太陽拳vs野球拳)   2013-02-08 14:00:00
用整數算 +1
作者: OnlyRD (里巷人)   2013-02-17 03:35:00
Q format.

Links booklink

Contact Us: admin [ a t ] ucptt.com