Pregunta

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?

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top