Show padding zeros using DecimalFormat

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"

Leave a Comment