Convert double to 2 decimal places?

• 11-19-2011, 06:07 PM
Convert double to 2 decimal places?
Hi,

Am trying to calculate the volume using 2 variables both of which are in cm and the requirement is to display in inches.

Code:

```length = cl.getUserLength(); diam = cd.getUserDiameter();       volume = ((diam / 2) * length) / 2.54;```
Both length and diam can only be entered in as whole numbers.
Thats my code so far. (diam / 2) is to get the radius and / 2.54 is to get it to inches. However for example if both measurements are say 10, i get a output of 19.68503937007874

I want it down to 2 decimal places. I have checked alot online and references to BigDecimal and DecimalFormat, however tutorials are very unclear on how to implement.

All help will be appreciated.
• 11-19-2011, 06:42 PM
Fubarable
Re: Convert double to 2 decimal places?
If you are going to be displaying the number on the console / standard output stream, then using System.out.printf should do the trick. Since a double is a floating point number, you can use something like %.2f as the format specifier to format your String.

For more on how to use this, please look here: formatting. Note that System.out.format works the same way as System.out.printf.
• 11-20-2011, 01:34 AM
pbrockway2
offtopic factoid
I agree with Fubarable: what you are trying to do is format a value for display rather than convert the value into something else (of necessity, less accurate).

You learn something here every day!

Quote:

I want it down to 2 decimal places.
I was worried that you choose a conversion factor of 2.54 which only has 3 significant places and, depending on the absolute magnitude of length and diam I thought there might be a problem. It turns out that 2.54 is accurate to umpteen decimal places: but only since 1959 when the "international foot" was invented and carefully aligned with metric units. A "survey foot" in the US is 12 inches each of 2.54000508cm.