Javascript Rouding in For

I have this line:

for (var j = 0; j<1; j = (j + 0.1).toPrecision(1))

I am trying to tune this statement to get 0, 0.1, 0.2, 0.3 to number 1.

At the moment, I get 0, 0.1, and then nothing, as if the result goes right through 1,

Just using j = j + 0.1, you get rounding errors, and I need the exact decimal place.

Any suggestions?

+3
source share
2 answers

Try this ... When you use toPrecision, its number is not greater, so it fails after the first iteration.

for (var j = 0; j<1; j = (parseFloat(j) + 0.1).toPrecision(1)) 
+1
source

Better to do

for (var jj = 0; jj < 10; ++ jj) {
   var j = jj / 10;
   ...
}

if you need accuracy.

+2
source

Source: https://habr.com/ru/post/1730208/


All Articles