• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

Javascript anomaly calculating sum of numbers.

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
ngobw
Asked:
ngobw
  • 2
2 Solutions
 
ozoCommented:
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
 
ngobwAuthor Commented:
Thanks for the answer.  It's a very interesting find!
0

Featured Post

Industry Leaders: 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!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now