Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

double decimal problems

 
Bredan Tomong
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • 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?
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • 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"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic