views:

689

answers:

4

I'm using DecimalFormat to format doubles to 2 decimal places like this:

DecimalFormat dec = new DecimalFormat("#.##");
double rawPercent = ( (double)(count.getCount().intValue()) / 
                            (double)(total.intValue()) ) * 100.00;
double percentage = Double.valueOf(dec.format(rawPercent));

It works, but if i have a number like 20, it gives me this:

20.0

and I want this:

20.00

Any suggestions?

+2  A: 

Use format "#.00".

ZZ Coder
that doesn't work either
mportiz08
You haven't showed us your print statement. If you do dec.format(percentage), the format will work.
ZZ Coder
A: 

Try using a DecimalFormat of "0.00" instead. According to the JavaDocs, this won't strip off the extra 0s.

saleemshafi
it's still stripping off an extra zero with the "0.00" format :(
mportiz08
+6  A: 

The DecimalFormat class is for transforming a decimal numeric value into a String. In your example, you are taking the String that comes from the format( ) method and putting it back into a double variable. If you are then outputting that double variable you would not see the formatted string. See the code example below and its output:

int count = 10;
int total = 20;
DecimalFormat dec = new DecimalFormat("#.00");
double rawPercent = ( (double)(count) / (double)(total) ) * 100.00;

double percentage = Double.valueOf(dec.format(rawPercent));

System.out.println("DF Version: " + dec.format(rawPercent));
System.out.println("double version: " + percentage);

Which outputs:

"DF Version: 50.00"
"double version: 50.0"
Dougman
thanks--that makes sense, and now it's working perfectly
mportiz08
A: 

you can try something like

DecimalFormat df = new DecimalFormat("0.000000"); df.setMinimumFractionDigits(0); df.setMinimumIntegerDigits(2);

This way you can ensure minimum number of digits before or after the decimal

Ashish