wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes problem while adding 2 numbers (double) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem while adding 2 numbers (double)" Watch "problem while adding 2 numbers (double)" New topic
Author

problem while adding 2 numbers (double)

sachin bal
Greenhorn

Joined: Mar 24, 2010
Posts: 9
Hi,

I have developed the a small program to calculate the addition of 2 numbers which are double. There seems to be some problem with the output specifically for the following 2 numbers 10.4 and 19.05. The output which I get after adding these two numbers is 29.450000000000003.

In case I add 10.4 and 29.05, I get the output as 39.45.

Can someone help me understand the reason for this discrepancy?

Regards

Sachin Bal
Shinil Mohan
Ranch Hand

Joined: Aug 24, 2011
Posts: 37

Can you try using DecimalFormat for getting the output you are looking for.

http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3594
    
  14

The reason is that floating point numbers can not represent every number exactly. They are generally an approximation of the actual number.

The two doubles both deviate a little bit from the real intended value, and when you add them, their deviation is added as well. In this particular case, the deviation becomes to big that it appears significant, and shows up in the output.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Check out our JavaBeginnersFaq, item #20.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
sachin bal
Greenhorn

Joined: Mar 24, 2010
Posts: 9
Hi All,

Thank you for all the help. I appreciate it.

Regards

Sachin Bal
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: problem while adding 2 numbers (double)
 
Similar Threads
printout "�" turns to u`
Incorect operations order when implementing math parser with JavaCC
Ternary operator - seeking advice
how to convert double as a currency
Attempting to reset a loop/ method