3

Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?

Note - I have read other posts on parseFloat(), but I have not found a good explanation as to why the problem occurs. (Or I just didn't understand it).

This code ...

var sum = parseFloat("1.001") + parseFloat(".001");

alert(parseFloat(sum));​

outputs ...

1.0019999999999998

I've read that adding sum.toFixed(2) will include only 2 decimal points.

However, I do not 100% understand why this long decimal occurs.

Does parseFloat(sum) represent sum in binary? If so, then 1.001 cannot be represented in binary since 1/2^x + ... can never equal .001 or 1/1000 exactly?

Community
  • 1
  • 1
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

2

This isn't specific to Javascript, but rather how IEEE Floating Point Numbers are represented internally that cause precision errors.

I won't reproduce the content here, but there are a bunch of resources available to help explain what is going on in your example.

Here is one: http://www.petebecker.com/js/js200006.html

Josh
  • 44,706
  • 7
  • 102
  • 124