8

Possible Duplicate:
Is double Multiplication Broken in .NET?

JavaScript code:

var n = 1; 
while ( n > 0 )
{
  n -= 0.1;
  document.body.innerHTML += n + "<br/>";
}

http://jsfiddle.net/UpUE6/4/

I expected:

0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0

But got this:

0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457e-16
-0.09999999999999987

Could anyone explain what's going on there?

Community
  • 1
  • 1
RobertO
  • 2,655
  • 1
  • 20
  • 18
  • 5
    Dupe of so many dupes [Strange loop on Java for 0.1 to 2](http://stackoverflow.com/questions/5400565/) or [Is double multiplication broken in .NET?](http://stackoverflow.com/questions/1420752/). See the [gory details](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html). – R. Martinho Fernandes Apr 13 '11 at 14:41

5 Answers5

11

From The Floating-Point Guide:

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
7

You're seeing an artifact of the way computers do floating-point arithmetic. See, for example, http://en.wikipedia.org/wiki/Floating_point#Machine_precision

Jonathan
  • 7,536
  • 4
  • 30
  • 44
6

This will solve your problem

http://jsfiddle.net/AVPNx/

var n = 1;
while ( n > 0 ){
    n -= 0.1;
    result = n.toFixed(1);
    document.body.innerHTML += result + "<br/>";
}
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
3

You're dealing with a floating point number. Check out the toFixed and toPrecision methods.

JamesB41
  • 703
  • 10
  • 20
1

Not all numbers can be represented exactly, even if they have a simple representation in decimal notation. This is because JavaScript uses IEEE 754 to represent floating point values, and thus uses base 2 instead of base 10. This leads to you not actually subtracting 0.1 (even though your source code says so), but some value close to it.

Oswald
  • 31,254
  • 3
  • 43
  • 68