[java] Best way to Format a Double value to 2 Decimal places

I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of decimal values in Java?

Is there any other better way of doing it than

 DecimalFormat df = new DecimalFormat("#.##");

What i want to do basically is format double values like

23.59004  to 23.59

35.7  to 35.70

3.0 to 3.00

9 to 9.00

This question is related to java

The answer is


No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".


An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.