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?
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.
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.
DecimalFormat isn't thread-safe, thus we should pay special attention when sharing the same instance between threads.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With