Solved

Javascript anomaly calculating sum of numbers.

Posted on 2009-05-05
3
246 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

726 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