日期:2014-05-16  浏览次数:20367 次

js中的浮点数
我看Professional JavaScript for Web Developers, 3rd Edition中第36页和第37页介绍浮点数时说:
Floating-point values are accurate up to 17 decimal places but are far less accurate in arithmetic
computations than whole numbers. For instance, adding 0.1 and 0.2 yields 0.30000000000000004
instead of 0.3. These small rounding errors make it diffi cult to test for specifi c fl oating-point values.
Consider this example:
JScript code

if (a + b == 0.3){ //avoid!
    alert(“You got 0.3.”);
}


Here the sum of two numbers is tested to see if it’s equal to 0.3. This will work for 0.05 and 0.25
and for 0.15 and 0.15. But if applied to 0.1 and 0.2, as discussed previously, this test would fail.
Therefore you should never test for specifi c fl oating-point values.
以上这是什么意思呢,同样是浮点数,为什么0.05+0.25或者0.15+0.15的和精确地等于0.3,而0.1+0.2不是呢?作者说的 whole numbers是什么啊?

------解决方案--------------------
whole number是整数的意思。
js本来就不适合作科学计算,十进制转化为二进制的过程以及逆反过程中可能会有损耗。
------解决方案--------------------
貌似是十进制的小数未必能精确的转换成对应的二进制,从而导致计算结果有小的出入