作者anawak (...)
看板Ajax
标题[问题] Javascript 诡异的计算问题
时间Sun Dec 8 06:37:02 2013
刚发现表单数值有一个诡异的数字: 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>
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.228.25.7
※ 编辑: anawak 来自: 61.228.25.7 (12/08 06:41)
1F:推 juicyroach:个人猜测是rounding error 12/08 10:36
2F:推 CaptainH:浮点数会有精度问题 所有语言都一样 12/08 11:25
3F:推 mrbigmouth:运算前先化为整数即可 12/08 12:26
4F:推 danny8376:楼上... 这边就是小数运算 化整数要算啥啊... 12/08 12:39
5F:→ danny8376:总之上面都有推到了 可以的话你改 /1000 就没这问题了 12/08 12:40
6F:→ TonyQ:这问题标准解之一是转整数运算没错。 12/08 13:37
7F:→ TonyQ:只是要运算的话,抓一下你精度要到小数几位处理就好。 12/08 13:40
8F:→ dlikeayu:用整数算 +1 12/08 14:00
9F:推 OnlyRD:Q format. 12/17 03:35