Class DecimalFormat , in package java.text , allows you to describe the format
into which a number should be converted. Here is an example, called a pattern :
In the pattern:
• 0 represents a digit that will appear (a 0 appears if it does not exist).
• # represents a digit that is optional (a blank appears if it does not exist).
• . is the decimal separator.
• , is the grouping separator
Other characters that appear in a pattern, like $ in the pattern above, appear in the
converted number. Below, we show four patterns and several numbers as they
appear in each. Note especially the use of % , which causes the number to be mul-
tiplied by 100 . Note also how the B 's, C 's, and $ were placed when using the third
pattern. Finally, note that if an integer is too big for the given pattern, more
spaces are used.
number "$###,###,#00.00" "##0.00%" "B#,B#0C.$C0"
5 "$05.00" "500.00%" "B5.0BC$C"
123.321 "$123.32" "12332.10%" "B1,23.3BC$C"
.321 "$00.32" "32.10%" "B0.3BC$C"
We have just scratched the surface of patterns in class DecimalFormat . The
patterns and various methods are designed to make it possible to parse and for-
mat numbers in any locale (see Sec. 5.5.2), including support for Western,
Arabic, and Indic digits. But this introduction is enough to get you started.
Here is how to use class DecimalFormat . First, create an instance of the
class, using the desired pattern as the argument of the constructor call, e.g.
DecimalFormat decform= new DecimalFormat("##0.00");
Then, to convert the value of an expression to a String using that pattern, call
method decform.format with the expression as argument, e.g.
String s= decform.format(4.56);
Is the decimal point optional?
Look at the pattern in the constructor call of the following statement:
DecimalFormat decform1= new DecimalFormat("###.##");
Because there is no 0 to the right of the decimal point, the decimal point is
optional and appears only if the fraction is nonzero:
decform1.format(25) is "25"
Make the decimal point mandatory by executing the following statement: