File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes double behaviour Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "double behaviour" Watch "double behaviour" New topic
Author

double behaviour

Sethu Prem
Greenhorn

Joined: Aug 10, 2005
Posts: 6
Hi ,

Can somebody explain why double is being treated differently in the following code piece ?
double d1= 33.30+33.40+33.30;
double d2= 33.40+33.30+33.30;
double d3= 33.30+33.30+33.40;
Among these only d3 gives me result of 100.0 other 2 gives me 99.9.


Seth
Jean-Sebastien Abella
Ranch Hand

Joined: Jul 29, 2005
Posts: 60
This is a very old problem with floating point. If you want exact value you must use BigDecimal.

This is due to a limitation in the value you can represent on a bit pattern as there is an infinite number of decimal value between 0 and 1 there is a need for some imprecision.
Paul Santa Maria
Ranch Hand

Joined: Feb 24, 2004
Posts: 236
Jean-Sebastien is, of course, absolutely right. The key two points are:

1. Floating point math is an *approximation* (integer and BigDecimal is
*exact*)
... and ...
2. The order you perform the individual calculations affects what
values the intermediate results round to, which in turn affects the
final result.

EXAMPLE:


Paul M. Santa Maria, SCJP
Sethu Prem
Greenhorn

Joined: Aug 10, 2005
Posts: 6
Thanks to both of you !!
 
Don't get me started about those stupid light bulbs.
 
subject: double behaviour