How to make 0 display as 0.00 using decimal format?
Asked Answered
L

2

13

I am using the following code to make numbers display with two decimal places and thousands comma separator.

public static String formatNumber(double amount){
    DecimalFormat formatter = new DecimalFormat("#,###.00");
    return formatter.format(amount);
}

For other numbers it is ok but 0 is returned as ".00" I want it to be "0.00" What should I change?

Limicolous answered 3/11, 2014 at 2:6 Comment(3)
how about "#,##0.00"?Mcwhirter
@HovercraftFullOfEels I thought you were swearing for second there ;)Sesquicarbonate
Also, the separator I think can be automatically set via setGroupingUsed(true). This way you will automatically have the separator show for thousands, millions, billions, ...Mcwhirter
C
13

Why not

return String.format("%.2f", amount);

That would format it correctly wouldn't it? (if amount is 123123.14233 then it would return 123123.14)

or

return String.format("%,.2f", amount); 

for commas within the number. (if amount is 123123.14233 then it would return 123,123.14)

Criswell answered 3/11, 2014 at 2:13 Comment(0)
L
23

The # means optional digit, so if you use 0 instead it will work:

    DecimalFormat formatter = new DecimalFormat("#,##0.00");

BTW: I think you need 3 ### not 4.

Leomaleon answered 3/11, 2014 at 2:10 Comment(0)
C
13

Why not

return String.format("%.2f", amount);

That would format it correctly wouldn't it? (if amount is 123123.14233 then it would return 123123.14)

or

return String.format("%,.2f", amount); 

for commas within the number. (if amount is 123123.14233 then it would return 123,123.14)

Criswell answered 3/11, 2014 at 2:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.