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
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
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
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
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:
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.