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?
format("%05d", yournumber); for zero-padding with a length of 5.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding.
Yes, include the + character, e.g. String. format("%+014.2f", -2.34); .
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With