简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM