• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

double decimal problems

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try follow coding. Guess what's the output?
int size = 55;
double total = 0.0;
for (int i = 0; i < size; i++) {
total += 0.1 + i;
}
System.out.println("Total is : " + total);
The answer is "Total is : 1490.4999999999995"
Any ideas about fixing the problem except using BigDecimal?
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have to assume that the problem is the rounding issue. doubles and floats both have decimals. In order to be precise with decimals you would need to have an infinite number of decimal places (of course impossible) therefore they are ALWAYS not quite exact.
BigDecimal is probably your best bet.
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey, I JUST saw this article in JavaWorld
http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html
So I thought that I would share it with you. How timely.
 
Without deviation from the norm, progress is not possible - Zappa. Tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic