3

Possible Duplicate:
Is JavaScript's Math broken?

<html>
<body>

<script type="text/javascript">
 var w = 0;
 var weight1 = parseFloat("0.6");
 var weight2 = parseFloat("0.3");
 w = weight1 + weight2;

 document.write("total weight: " + w);
</script>

</body>
</html>

Why does this print 0.8999999999999999 and not 0.90000000

Community
  • 1
  • 1
kal
  • 28,545
  • 49
  • 129
  • 149

5 Answers5

3

Because the number 9/10 cannot be represented cleanly in base 2, just like the number 1/3 cannot be cleanly represented in base 10.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

The way floating point numbers are made, certain values cannot be accurately represented. This is a limitation of this data type, there is little to nothing you can do to fix it, you have to just anticipate this, and make use of round or something.

http://en.wikipedia.org/wiki/Floating_point

LostInTheCode
  • 1,724
  • 2
  • 15
  • 22
0

Simple rounding errors. floating point numbers are not precise. This makes comparisons a little more complicated. Eg. If (my_float == 3.0) will invariably fail.

winwaed
  • 7,645
  • 6
  • 36
  • 81
-1

To answer your question - floating points have as much precision as your RAM can allow. If you create a floating number 1 - it may actually be 1.000000000000000000001

Obviously your solutions include rounding the number, or using ints

Mikhail
  • 8,692
  • 8
  • 56
  • 82
  • 3
    This has nothing to do with RAM, and specifying the exact float value 1 will never yield anything but 1. This has to do with repeating numbers -- just like 1/3 can't be represented as a finite digit sequence in base 10, the number 1/10 cannot be represented as a finite digit sequence in base 2. – cdhowie Nov 12 '10 at 22:16
  • I was definitely wrong on that one. here's what I tested, and concluded incorrectly: ((1/10) * 1e63) - 1e62 = 1.141798154164768e+46 – Mikhail Nov 15 '10 at 20:40