Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of DecimalFormat for the following case

Tags:

java

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?

like image 568
Cheok Yan Cheng Avatar asked Feb 06 '10 14:02

Cheok Yan Cheng


People also ask

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.

What is DecimalFormat?

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 DecimalFormat thread safe?

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

How do you convert to 2 decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.


1 Answers

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);
like image 136
Gladwin Burboz Avatar answered Sep 16 '22 11:09

Gladwin Burboz