0

Why does this occur:

window.onload = function(){
    var bob=new Number(1);  
    for (var i=0; i<8 ;i++){        
        bob=Number(bob+1.1)             
    }

}

Alerts: 2.1

3.2

4.300000000000001

5.4

6.5

7.6

8.7

9.799999999999999

deach
  • 360
  • 1
  • 2
  • 12
  • See http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem for workarounds and discussion of this problem. – jfriend00 Nov 02 '11 at 01:43
  • possible duplicate of [Is JavaScript's Math broken?](http://stackoverflow.com/questions/588004/is-javascripts-math-broken) – Tobias Cohen Nov 02 '11 at 01:47

4 Answers4

0

Because in Javascript, "numbers" default to floating point. Even "i" ;-) And, of course, "Bob".

And floating point numbers are approximations.

If you want, you can use "floor()" and "ceil()"

PS: You can also use parseInt() to convert a float to an int:

parseInt (4.33) // Result = 4

Or round():

round (3.2 + 1.1) // 4.3, not 4.300000000000001
paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

Because the javascript Number is actually a double precision float:

From the spec:

4.3.19
 Number value
  primitive value corresponding to a double-precision
  64-bit binary format IEEE 754 value
david
  • 17,925
  • 4
  • 43
  • 57
0

It's rounding issues. 4.3 has no exact representation in binary.

How exactly numbers get stored in JavaScript is actually implementation-specific, but it is always a binary floating point.

Edit:

Looks like my information is a little outdated. The standard now specifies doubleprecision 64-bit format IEEE 754 values

Links:

Dennis
  • 14,264
  • 2
  • 48
  • 57
  • 1
    There are fixed formats that would be able to store 4.3 exactly. The problem is that javascript uses floats. – david Nov 02 '11 at 01:50
0

The problem has to do with how the computer, which works on base(2), calculates base(10) arithmetic. There's a lot of articles explaining the nuances.

If you haven't solved your problem yet, whenever you use floating point numbers, you should also massage the output with the appropriate function.

I typically use number.toFixed() which will round to an appropriate number of decimal places.

hafichuk
  • 10,351
  • 10
  • 38
  • 53
  • The problem is that the designers of JavaScript decided to use a format that works that way, and not provide a number type that handles base 10 correctly by default. – nnnnnn Nov 02 '11 at 02:11