剛發現表單數值有一個詭異的數字: 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>