1

I've just been experimenting with for loops and noticed this when I changed the increment value to i += 0.1.

for (i = 0; i < 100; i += 0.1) {
    console.log(i);
}

In the console it returns

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

By the time you reach 100

99.69999999999861
99.7999999999986
99.8999999999986
99.9999999999986

What is the reason behind this? I imagine this would be frustrating if you are trying to search for a number. Is there a way to round to the nearest 10th? I know how to round with Math.floor, ~~, a | 0, but only to the nearest whole integer.

Bryan Chen
  • 42,570
  • 18
  • 109
  • 136
var name
  • 71
  • 1
  • 1
  • 5

2 Answers2

1

I guess you are looking for something like this:

for (i = 0; i < 100; i += 0.1) {
    console.log(Math.round(i * 100) / 100);
}
Pritam Banerjee
  • 15,297
  • 10
  • 71
  • 92
0

Simple solution: Multiply by ten, add one, divide by ten.

for (var i = 0; i < 100; i = (i * 10 + 1) / 10) {
  console.log(i);
}

for (var i = 0; i < 100; i = (i * 10 + 1) / 10) {
      console.log(i);
    }
Kyle Lin
  • 786
  • 6
  • 16
  • Multiplying an imprecise value by 10 doesn't make it more precise. Better avoid floating point calculation as far as possible. `for (var i = 0; i < 1000; i++) { console.log(i / 10.0); }` – Roland Illig Dec 20 '16 at 00:37
  • You are not multiplying an "imprecise" floating point value by 10, but rather multiplying an integer by 10 and adding 1 and finally dividing by 10, to avoid the alternative, which is adding 0.1. With the former, you are performing integer addition and then dividing by ten to produce a float (which is precise enough for the purpose of answering this question). With latter, you are directly adding floats, which is not precise enought. – Kyle Lin Dec 20 '16 at 00:53