• Post Reply Bookmark Topic Watch Topic
  • New Topic

double (float) accuracy  RSS feed

 
Tim Cao
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a bit of problem with the double accuracy. E.g

double os = 0.05;
os += 0.05;
os += 0.05;
System.out.println(os);

And I get
0.150000000002 (or something)

I aleardy tried this program with various jdk versions and
platforms and still get the same result. Of course the accuracy
of the computation is not affected, but it is a small inconvinience
for outputting purposes.

Anyone knows how to get 0.15 for the above code?

Cheers,

T.
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avoid float & double for any calculations that require an exact answer. Use BigDecimal instead.
Or, if you are not worried about the exact answer but your only concern is to display the result properly, you can use DecimalFormat.


[ July 27, 2004: Message edited by: Mani Ram ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!