aspose file tools
The moose likes Java in General and the fly likes double (float) accuracy Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "double (float) accuracy" Watch "double (float) accuracy" New topic
Author

double (float) accuracy

Tim Cao
Ranch Hand

Joined: Jul 26, 2004
Posts: 37
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

Joined: Mar 11, 2002
Posts: 1140
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 ]

Mani
Quaerendo Invenietis
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: double (float) accuracy
 
Similar Threads
round
Strange value returned
rounding off in java
symbol not found?
How can I have a sleep method that make a Thread sleeps for EXACTLY the time I set?