This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Issue with a double ... again Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Issue with a double ... again" Watch "Issue with a double ... again" New topic

Issue with a double ... again

Sergey Gorovoy

Joined: Jul 28, 2001
Posts: 3
I know that there are issues arising from using primitives of data type double in mathematical expressions. Somewhere in the earlier polsts it was suggested to use Math.round(a), where a is a double. However, when I execute the following:
double x = 27.475;
double y = 7.22;
double z = x - y;
System.out.println("x - y = " + Math.round(z));
I get "x - y = 20", not 20.255. If I do not use Math.round, I get 20.255000000000003. Now, how would one do the basic calculations then and get the correct result?
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Sergey,
You are getting the correct result. Math.round only returns an integer. If you want to "print" out the answer formatted then you can make use of java.text.SimpleDecimalFormat.
SimpleDecimalFormat sdf = new SimpleDecimalFormat( "#.000" );
System.out.println( "x - y = " + sdf.format( z ) );
Sergey Gorovoy

Joined: Jul 28, 2001
Posts: 3
But what about the situation when the value of X and Y is being assigned dynamically, which may result in more than 3 decimal positions for Z? Is there any way to dynalically "round" the result?
jQuery in Action, 2nd edition
subject: Issue with a double ... again
Similar Threads
Mixed bag
why different output whilre using round() function
Apply function names as parameters in other functions
Plot update error - JMathPlot
Several questions about this program