1

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

logic8
  • 874
  • 9
  • 21
  • 1
    Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Randy Casburn May 16 '18 at 00:39

1 Answers1

2

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);
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60