<$BlogRSDURL$>

Monday, April 19, 2004

Javascript: When 44.30 + 22.18 does not equal 66.48... 

Well, there is always something new to learn. Some wasted time with doing Javascript has taught me a lot. Before starting check out here for a very good Javascript FAQ. Anything you think is wrong with language check there ( comp.lang.javascript FAQ ).

Now to my problem. I was joustling with issue where the two figures were not adding to what they should. Somewhat like that Title of the post. It was adding up to 66.479999999. I was like totally perplexed with alternately cursing Microsoft (was checking my code in Internet Explorer :) ) for buggy javascript implementation and scrouging the web with google.

Cutting it short the reason lies with the way the Javascript numbers are represented. It is something called IEEE-754 Doubles, which has a resolution(accuracy) of 53 bits, giving an accuracy of 15-16 decimal digits; integers up to about 9e15 are precise, but few decimal fractions are. Given this, arithmetic is as exact as possible, but no more. Operations on integers are exact if the true result and all intermediates are integers within that range.

In particular, non-integer results should not normally be compared for equality; and non-integer computed results generally need rounding. (From the site mentioned above.)

0 Comments:

Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?