File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes rounding a double Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "rounding a double" Watch "rounding a double" New topic

rounding a double

Y Cheong

Joined: Jan 19, 2003
Posts: 9
I have a double and I want to round this to 2 decimal places. I have seen in another thread, that u can multiply this by 100, then use Math.round, then divide by 100.
This however does not seem to work
David Crossett
Ranch Hand

Joined: Feb 05, 2003
Posts: 102
Aha! You have learned how floats and doubles are not very accurate! Here, try this:

What this code does, of course, is multiply the number by 100, then add .5, then divide by 100 to get back to the hundredths place. Try to work this code out by hand with a calculator and you'll see how it works. The Math.floor() function rounds a number to the nearest integer, NOT greater than the number is. Hence, we bring the hundredths place out to 'integer land' by multiplying by 100 ( or 10 for tenths, or 1000 for thousandths ). Then we add .5 to see if we should go up to the next integer or not ( if the number is 6.456, then we multiply by 100 to get 645.6, then add the .5 making it 646.1, then divide by 100 to get back to 6.46).
I hope this helps - I'm not sure I explained this very well, but I know the code works for what you're trying to do!

David Crossett
-nothing important to say, but learnin' plenty-
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
I have seen in another thread, that u can multiply this by 100, then use Math.round, then divide by 100
What may have gone wrong here is this: Math.round() returns an integer (either int or long, depending on its arguments). If you take an integer / 100, Java will perform integer division, which rounds the result down, much like the floor() function. E.g. 167 / 100 is 1. Not 1.67 as you might expect, not 2 (integer division rounds towards zero, not towards the nearest integer.) You probably do not want integer division at this point, you want floating-point division. You need to tell the compiler that at least one of the numbers involved in the deivision is floating-point. The easy way to achieve this is to divide by 100.0 rather than 100.
Note that in David's example above, 100.0 was not necessary, because he used the floor() method - which returns a double, not an integer. So it didn't matter if the other number isn the division was 100 or 100.0; either way, the division would use floating-point arithmetic.

"I'm not back." - Bill Harding, Twister
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: rounding a double