Solved

Javascript anomaly calculating sum of numbers.

Posted on 2009-05-05
3
245 Views
Last Modified: 2013-11-19
This script boggles me. When the numbers are added, it seems that it doesn't amount to 100, but instead gave a value of 100.000.... 001

Can anyone explain to me why this is so? Thanks!

NOTE: Substitute the plus sign before testing it.
<html>
<head>
<script type='text/javascript'>
function holygrail() {
     sum = 51.4 'plus' 14 'plus' 14 'plus' 11.4 'plus' 7.5 'plus' 1.7;
     alert(sum);
}
</script>
</head>
<body onload='javascript:holygrail();'>
</body>
</html>

Open in new window

0
Comment
Question by:ngobw
  • 2
3 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 500 total points
ID: 24303169
binary floating point numbers can't represent 51.4 or 11.4 or 1.7 exactly, so you really have something like
51.3999999999999999999999999999996844556379 + 14 + 14 + 11.4000000000000000000000000000000788860905 + 7.5 + 1.6999999999999999999999999999999901392387
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 500 total points
ID: 24303294
0
 

Author Closing Comment

by:ngobw
ID: 31577946
Thanks for the answer.  It's a very interesting find!
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Nicole
This is a research brief on the potential colonization of humans on Mars.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question