• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

double behaviour

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Sethu Prem
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to both of you !!
 
WARNING! Do not activate jet boots indoors or you will see a tiny ad:
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!