logic8
logic8

Reputation: 935

Simple for loop is throwing me for a loop - decimal increment error

I'm attempting a simple for loop but getting odd results. I'm incrementing by a decimal (.02) but it seems to be adding incorrectly.

here is the loop:

for ( var a = 0; a <= 10; a += .02 ) {

    console.log(a);

}

the results are fine for a bit..

0, 0.02, 0.04, 0.06, 0.08, 0.1

then it gets a little strange:

0.12000000000000001

and then it gets really far out:

0.19999999999999998 ... 9.999999999999876

Aside from the odd decimal addition it stops short of my end goal of 10.

I've tried for (var a = 0; a <= 10; a = (Math.round(a * 100)/100) + .02 ) (which gets me closest but still runs odd), parsefloating a, even a += 2/100.

Same results in a while loop.

Any ideas would be great!

EDIT: Although there are some workarounds for floating point precision in this post "How to deal with floating point number precision in JavaScript?" - I'm not sure how many would fit elegantly in a loop construct

Upvotes: 1

Views: 108

Answers (1)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can use toFixed(2)

for ( var a = 0; a <= 10;) {
    console.log(a);
    a += 0.02;
    a = +a.toFixed(2)
}
   
// Another possible way is
var limit = 10;
var increment = 0.02;
for ( var a = 0; a <= limit * 100; a += increment * 100) {
    console.log(a / 100);
}

Upvotes: 2

Related Questions