-2

When I run a β€œFor” loop and I log the index used in it with increments of 0.1 , starting from 1, the outcome is not a number with a single decimal digit, but something with multiple decimal digits (code and results are shown here below).

for (let i = 1; i <= 2; i += 0.1) {
    console.log(i);
};

What I expected is to see the following series:

1

1.1

1.2

1.3

...

instead what I actually get is:

1

1.1

1.2000000000000002

1.3000000000000003

1.4000000000000004

1.5000000000000004

1.6000000000000005

1.7000000000000006

1.8000000000000007

1.9000000000000008

This happens in every browser, in the same way either I compile the loop directly in the Console DOM or I code within Visual Studio Code. Does anyone have an explanation about it?

ThS
  • 4,597
  • 2
  • 15
  • 27
Antonio
  • 11
  • 3
  • 2
    Possible duplicate of https://stackoverflow.com/questions/588004/is-floating-point-math-broken?noredirect=1&lq=1 – Robin Jul 27 '19 at 15:31
  • Thanks everyone. I know understand that the issue is with the conversion of a decimal system into binary. – Antonio Jul 27 '19 at 16:42

1 Answers1

0

Have you tried incrementing by 0.100000000000000?

Or using i = i.toFixed(1)? This will round the number to one decimal place. May not be what you need as toFixed will convert the number to a string

DialDT
  • 422
  • 4
  • 6