Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript adding 0.1 to 0.2 causes 0.30000000000000004 [duplicate]

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.

like image 625
Mustafa Avatar asked Oct 23 '25 15:10

Mustafa


1 Answers

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
like image 180
Blaster Avatar answered Oct 25 '25 05:10

Blaster