Javascript Rouding in For statement
-
23-09-2019 - |
Question
I have this line:
for (var j = 0; j<1; j = (j + 0.1).toPrecision(1))
I'm trying to set up this statement so I get 0, 0.1, 0.2, 0.3 up to the number 1.
At the moment I get 0, 0.1 and then nothing as if the result goes straight passed 1,
Simply using j = j + 0.1 produces rounding errors and I need the precise decimal place.
Any suggestions?
Solution
Try this... When you use toPrecision its not number any more so it fails after the first iteration.
for (var j = 0; j<1; j = (parseFloat(j) + 0.1).toPrecision(1))
OTHER TIPS
It's better to do
for (var jj = 0; jj < 10; ++ jj) {
var j = jj / 10;
...
}
if you need precision.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow