Show padding zeros using DecimalFormat
Try this code:
BigDecimal decimal = new BigDecimal("100.25");
BigDecimal decimal2 = new BigDecimal("1000.70");
BigDecimal decimal3 = new BigDecimal("10000.00");
DecimalFormat format = new DecimalFormat("###,###,###,###,###.##");
format.setDecimalSeparatorAlwaysShown(true);
format.setMinimumFractionDigits(2);
System.out.println(format.format(decimal));
System.out.println(format.format(decimal2));
System.out.println(format.format(decimal3));
Result:
100.25
1,000.70
10,000.00
Use format "#.00".
You can try something like:
DecimalFormat df = new DecimalFormat("0.000000");
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(2);
This way you can ensure the minimum number of digits before or after the decimal
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"