homepage Welcome to WebmasterWorld Guest from 54.167.11.16
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Weird floating bug (and solution) though explenation appreciated!
JAB Creations




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

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);
}
}

 

alias




msg:4197142
 1:14 pm on Sep 6, 2010 (gmt 0)

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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved