I have the following decimal format previously :
private static final DecimalFormat decimalFormat = new DecimalFormat("0.00");
So,
it can change :
0.1 -> "0.10"
0.01 -> "0.01"
0.001 -> "0.00"
What I wish is
0.1 -> "0.10"
0.01 -> "0.01"
0.001 -> "0.001"
Is it possible I can achieve so using DecimalFormat?
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.
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.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
DecimalFormat class is not "Thread Safe". So you are better off having static String variable for this format while you should define the DecimalFormat object within your method required method.
Static variable:
private static final String decimalFormatStr = "0.00#";
.
Local variable in method:
DecimalFormat decimalFormat = new DecimalFormat(decimalFormatStr);
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