Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show padding zeros using DecimalFormat

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?

like image 765
mportiz08 Avatar asked Nov 16 '09 02:11

mportiz08


People also ask

How can I pad an integer with zeros on the left?

format("%05d", yournumber); for zero-padding with a length of 5.

How do you keep leading zeros in Java?

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.

How do you add a leading zero to a double in Java?

Yes, include the + character, e.g. String. format("%+014.2f", -2.34); .

How do you show float up to 2 decimal places?

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 %.


2 Answers

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" 
like image 198
Doug Porter Avatar answered Oct 05 '22 15:10

Doug Porter


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 
like image 33
Victor de la Cruz Avatar answered Oct 05 '22 16:10

Victor de la Cruz