For loop problem

I’m not good with JavaScript so please, if there is a simple solution/explanation, I would appreciate it.

Now on to my problem…

I’ve been using a for loop to speed up repetitive tasks and it seems to work great, till now.


<script type="text/javascript">

var count=0;

for (count=0;count<30;count+=2.4) //2.4 doesn't work consistently//
	{
		document.write(count+"<br />");
	}

</script>

The results I get start out correct then go wrong.

FireFox (3.6.16)____________________Results with IE 8____________________Results with Opera
0________________________________0________________________________0
2.4______________________________2.4_______________________________2.4
4.8______________________________4.8_______________________________4.8
7.199999999999999________________7.199999999999999_________________7.2
9.6______________________________9.6_______________________________9.6
12______________________________12________________________________12
14.4____________________________14.4_______________________________14.4
16.8____________________________16.8_______________________________16.8
19.2____________________________19.2_______________________________19.2
21.599999999999998______________21.599999999999998_________________21.60
23.999999999999996______________23.999999999999996_________________23.999999999999996
26.399999999999995______________26.399999999999995_________________26.399999999999995
28.799999999999994______________28.799999999999993_________________28.799999999999994

If I use…

<script type="text/javascript">

var count=0;

for (count=0;count<30;count+=1) //1, 2, 3, etc.. works fine//
	{
		document.write(count+"<br />");
	}

</script>

OR

<script type="text/javascript">

var count=0;

for (count=0;count<30;count+=1.5) //1.5 works fine//
	{
		document.write(count+"<br />");
	}

</script>

It counts like it should.

So why is it when I use “2.4” it doesn’t count properly?
And why does it produce different results in different browsers?

You could use this hacky addition to sort the rounding out:

for (count=0;count<30;count+=2.4)
    {
        document.write(Math.round(count*10)/10+"<br />");
    }

That worked for me. Thank You.

It still doesn’t make sense why it doesn’t work without the fix and why different browsers give different results.

Again, thank you.

EDIT:

Another suggestion I got was to use…

for (count=0;count<30;count+=2.4)
{
document.write(count.toFixed(1)+"<br />");
} 

Which works as well, just has a permanent float which is not a problem (for this project).

You’re right, it doesn’t make sense.

Here’s an article that can help to explain why.
Why I Love ECMAScript 4: Real Decimals

Thanks for the help. Still kinda Greek to me, but it helped.

Nice link. Will be interesting to see if the rounding or 1DP solutions above remain quicker than the proposed decimal types.