Richard Richard - 6 months ago 13
Java Question

Java Double Format to show 2 decimal points even when zero

I want to print out double values onto the screen with 2 decimal points. So far this line has worked perfectly:

System.out.println(new DecimalFormat("$#,###.##").format(value));


For inputs like:

double value = 82348238482834.23482348;


It prints out:

$82,348,238,482,834.23


Which is exactly what I want. However, if I have the input
0
I want it to print out
$0.00
. With the above format line it prints out
$0
. I tried changing the above code to:

double value = 0;
System.out.println(new DecimalFormat("$#,###.00").format(value));


But that printed out
$.00
. I could just do this:

if(value == 0) {
System.out.println("$0.00");
}


It works but it's very ugly. Is there any other way to solve this issue?

Answer

Use:

System.out.println(new DecimalFormat("$#,##0.00").format(value));

Changed:

"$#,##0.00"

Like Jon said, 0 indicates a digit so it includes zero, # indicates a digit but zero shows as absent.

For more info on DecimalFormat.