views:

34

answers:

3

Hi

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?

+1  A: 

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)) 
Bharat
+2  A: 

It's better to do

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

if you need precision.

KennyTM
yes, a bit more readable :-)
Alex
A: 

Thanks for the answer, it does exactly what I needed.

I also found Rajah's answer which also produces the numbers I want.

YsoL8
This isn't an answer to your question. You should post it as a comment.
Mark Byers