# Thread: Convert double to 2 decimal places?

1. Member
Join Date
Nov 2011
Posts
26
Rep Power
0

## 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.

Java 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.

2. ## 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.
Last edited by Fubarable; 11-19-2011 at 07:44 PM.

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14

## 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!

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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•