Take the 2-minute tour ×

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){
            // doIt(max,i);
            recur(max, i + 0.1);                
    } else {
        // OK

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.

share|improve this question
The question appeared a few minutes ago too (the answers are identical, copy-paste): stackoverflow.com/questions/11284981/… –  Rob W Jul 1 '12 at 19:43
Downvoting does not help, it did not appear in the similar questions part.. ANd there is much examples in every language, but each one of is downvoted.. Why? –  Mustafa Jul 1 '12 at 19:59
Not my downvote. Upon hover over the downvote icon, you see "This question does not show any research effort; it is unclear or not useful (click again to undo)". This question has been asked several times, and was easily found by entering the keywords in the search engine/Google. Copy-paste your title in Stack Overflow's search engine, and several duplicates appear. Same for Google –  Rob W Jul 1 '12 at 20:10
add comment

marked as duplicate by Oli Charlesworth, Robert Harvey Jul 1 '12 at 19:45


2 Answers

This is expected. Floating point operations on computers have small accuracy errors like this because of the way they are stored internally in a computer. For more information, I recommend you read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Questions similar to this get asked quite a lot. See this.

share|improve this answer
If you're aware that this is essentially a duplicate, you should just vote-to-close as a duplicate, rather than posting an answer... –  Oli Charlesworth Jul 1 '12 at 19:45
add comment

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
share|improve this answer
add comment
