Click to See Complete Forum and Search --> : add up two numbers and wrong result!!


everest
07-27-2004, 02:27 AM
Hello everyone,

does anybody know, why this simple code return bad result?

<a href="javascript: alert(67.60 + 13.60);">test</a>

Thanx for help!
P.

Pittimann
07-27-2004, 02:37 AM
Hi!

Taken from http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/number.html#1207032 :

0.124.toFixed(2) returns "0.12".

0.125.tofixed(2) returns "0.13", because 0.125 is exactly halfway between 0.12 and 0.13.

0 .126.tofixed(2) returns "0.13".

Given this convention, one might expect 0.045.toFixed(2) to return "0.05", but it returns "0.04". This is because of the way computers represent IEEE 754 floating-point numbers. The IEEE 754 standard uses binary fractions (fractions of 0's and 1's after the dot). Just as some numbers, such as 1/3, are not representable precisely as decimal fractions, other numbers, such as 0.045, are not precisely representable as binary fractions. The IEEE 754 standard dictates that 0.045 be approximated to 0.04499999999999999833466546306226518936455249786376953125, which is precisely representable as a binary fraction. This approximation is closer to 0.04 than to 0.05, so 0.045.toFixed(2) returns "0.04".
--------------------
Something like that will give you a correct result:

<a href="#" onclick="alert(Math.round((67.60 + 13.60)*100)/100);return false;">test</a>

Cheers - Pit