Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make 0 display as 0.00 using decimal format?

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?

like image 509
Hiten Naresh Vasnani Avatar asked Nov 03 '14 02:11

Hiten Naresh Vasnani


People also ask

How do you display upto 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

What is the decimal format?

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.

Is decimal format thread safe?

DecimalFormat isn't thread-safe, thus we should pay special attention when sharing the same instance between threads.

What is the use of DecimalFormat in Java?

You can use the DecimalFormat class to format decimal numbers into locale-specific strings. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.


1 Answers

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)

like image 51
EDToaster Avatar answered Sep 19 '22 00:09

EDToaster