Possible Duplicate:
Javascript Math Error: Inexact Floats
I have the following code to make an animation (doIt does the animation but not related).
function recur(max, i){
console.log("i: " + i);
if ( i <= 1){
setTimeout(function(){
// doIt(max,i);
recur(max, i + 0.1);
},100);
} else {
// OK
}
}
recur(16,0);
However, the i values are not consistent. For the following code the output is (Google Chrome 20):
i: 0
i: 0.1
i: 0.2
i: 0.30000000000000004
i: 0.4
i: 0.5
i: 0.6
i: 0.7
i: 0.7999999999999999
i: 0.8999999999999999
i: 0.9999999999999999
i: 1.0999999999999999
Why is this happening? I want 0.3 not a so close number. Unfortunately this happens in every iteration.
To output 0.3, you can use toFixed and floating point numbers have slight mis-calculations as @Oleksi pointed out.
console.log((0.1 + 0.2).toFixed(1)); // 0.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With