Welcome to WebmasterWorld Guest from 54.161.187.250

Forum Moderators: open

Message Too Old, No Replies

Weird floating bug (and solution) though explenation appreciated!

   
4:31 am on Sep 6, 2010 (gmt 0)

WebmasterWorld Senior Member jab_creations is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I encountered some weird float bug that did what it wanted and not what I told it to do...unless JavaScript is supposed to act like a total spazz when it comes floats?

Floating Bug
function floating_bug(i)
{
if (i==undefined) {i = 1.0;}

if (i!=0)
{
document.getElementById('status').value=document.getElementById('status').value+'\n'+i;
i = i-.1;
setTimeout(function() {floating_bug(i);},700);
}
}


...with that code I get the following results...

1
0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457e-16
-0.09999999999999987
-0.19999999999999987
-0.2999999999999999
-0.3999999999999999
-0.4999999999999999
-0.5999999999999999
-0.6999999999999998
-0.7999999999999998
-0.8999999999999998
-0.9999999999999998
-1.0999999999999999
-1.2
-1.3
-1.4000000000000001
-1.5000000000000002


Those results make no sense because I did not program the script to do wacky things.

I did come up with a fix though I would appreciate an explanation for why the browsers are giving spazz results for floats? Here is the same script though functioning as intended...

- John

Floating Bug Fix
function floating_bug_fixed(i)
{
if (i==undefined) {i = 1.0;}

if (i!=0.0)
{
document.getElementById('status').value=document.getElementById('status').value+'\n'+i;
i = i-.1;
var ii = i.toFixed(1);
setTimeout(function() {floating_bug_fixed(ii);},700);
}
}
1:14 pm on Sep 6, 2010 (gmt 0)

10+ Year Member



Have a read for it, 'javascript floating point precision' -- there's really a lot of material on that out on the net.

When you really think about how it works -- it doesn't act like a spazz. There's no real way to manipulate floats precisely in JavaScript.

So, don't rely on floats, use integers or double check all your code and do toFixed conversions.