Solved

Javascript anomaly calculating sum of numbers.

Posted on 2009-05-05
3
243 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
Comment Utility
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
Comment Utility
0
 

Author Closing Comment

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

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

728 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now