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?
Use format "#.00".
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:
Which outputs:
Try this code:
The output is: 10.00 20.00 0.00
Try this code:
Result:
You can try something like:
This way you can ensure the minimum number of digits before or after the decimal
I found my small test program useful and want to share it with you. Enjoy.
This results in: