-= 0.1 strange result
Possible Duplicate:
Is double Multiplication Broken in .NET?
号
javascript代码:
1 2 3 4 5 6 | var n = 1; while ( n > 0 ) { n -= 0.1; document.body.innerHTML += n +"<br/>"; } |
http://jsfiddle.net/upue6/4/
我期望:
1 2 3 4 5 6 7 8 9 10 | 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 |
号
但得到了:
1 2 3 4 5 6 7 8 9 10 11 | 0.9 0.8 0.7000000000000001 0.6000000000000001 0.5000000000000001 0.40000000000000013 0.30000000000000016 0.20000000000000015 0.10000000000000014 1.3877787807814457e-16 -0.09999999999999987 |
有人能解释一下那里发生了什么事吗?
你看到的是计算机做浮点运算的方式。例如,请参见http://en.wikipedia.org/wiki/floating_point machine诳precision
从浮点指南:
Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and
instead I get a weird result like
0.30000000000000004?Because internally, computers use a
format (binary floating-point) that
cannot accurately represent a number
like 0.1, 0.2 or 0.3 at all.When the code is compiled or
interpreted, your"0.1" is already
rounded to the nearest number in that
format, which results in a small
rounding error even before the
calculation happens.
号
这可以解决你的问题
http://jsfiddle.net/avpnx/
1 2 3 4 5 6 | var n = 1; while ( n > 0 ){ n -= 0.1; result = n.toFixed(1); document.body.innerHTML += result +"<br/>"; } |
你在处理一个浮点数。查看tofixed和toprection方法。
并非所有的数字都能精确地表示,即使它们有一个简单的十进制表示法。这是因为JavaScript使用IEEE754表示浮点值,因此使用基2而不是基10。这不会导致实际减去0.1(即使您的源代码这么说),但会有一些接近它的值。