Richard
Richard

Reputation: 6116

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?

Upvotes: 1

Views: 9419

Answers (2)

Jagger
Jagger

Reputation: 10524

I do not understand why people still use this DecimalFormat stuff. To achieve what you want just use System.out.printf with the following pattern.

System.out.printf("%,.2f%n", value);

If the value is 0 it will be always printed as 0.00 or 0,00 depending on locale.

Upvotes: 2

sebenalern
sebenalern

Reputation: 2561

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.

Upvotes: 7

Related Questions