开发者

Javascript Rouding in For statement

I have this line:

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

I'm try开发者_运维知识库ing 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?


It's better to do

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

if you need precision.


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)) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜