Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why does 1.4 + 1.2 = 2.5999999999996 1

Status
Not open for further replies.

marcp

Programmer
Jul 18, 2001
2
US
try making an alert box with the code

Code:
alert(1.2+1.4);

i get the result 2.59999999999996. anyone know why or what i can do to solve this problem?? Thanks.
 
I don't know how to fix it, but the problem is because the decimal part of the equation is sent to the co-processor, and when it is sent back to processor the data losses a little accuracy. Sorry I couldn't help with the answer, the way I solved the problem when I was making a calculator program was to multiply the numbers until they are both whole numbers, then to divide at the end.
 
thanks for the speedy reply, your solution sounds like a good work-around.
 
The cause of the problem is that math on a computer is done in binary. Just as there are some fractions that can't be precisely represented in decimal (like 1/3 = .333333333...) there are some fractions that can't be precisely represented in binary. Surprisingly, this includes almost anything in 10ths. Where decimal is tenths, hundreths, thousandths, etc., binary is halves, quarters, eighths, sixteenths, etc.

I tried using the same trick mayfair did for doing calculations - I did monay calculations using cents instead of dollars and cents, but ran into the same problem anyway, when I divided by 100 to convert cents back to dollars and cents, I got inaccuracies. I ended up parsing the resulting number as a string to insert the decimal point in the correct place.

Considering how much Javascript is used in forms for shopping carts, etc., wouldn't you think they'd at least give us a more accurate way of doing this? Or at least a "money" object, or something? Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Here's one way:

<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!--
// Round to the Tenths
alert(Math.round((1.2 + 1.4)*10)/10);

// Round to hundredths
alert(Math.round((1.23 + 1.45)*100)/100);
//-->
</SCRIPT>
- tleish
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top