Java Reference
In-Depth Information
// Format a double value for an Italian locale
result
= format.getInstance(Locale.ITALIAN).format(83.404);
System.out.println(result);
// Parse a String into a Number
try {
Number num = format.parse("75.736");
System.out.println(num);
} catch (java.text.ParseException ex){
System.out.println(ex);
}
To format using a pattern, the DecimalFormat class can be used along with
NumberFormat . In the solution to this recipe, you saw that creating a new Decim-
alFormat instance by passing a pattern to its constructor would return a Number-
Format type. This is because DecimalFormat extends the NumberFormat class.
Because the NumberFormat class is abstract, DecimalFormat contains all the
functionality that NumberFormat contains, plus added functionality for working with
patterns. Therefore, it can be used to work with different formats from the locales just
as you have seen in the previous demonstration. This provides the ultimate flexibility
when working with double or long formatting.
As mentioned previously, the DecimalFormat class can take a string-based pat-
tern in its constructor. You can also use the applyPattern() method to apply a pat-
tern after the fact. Each pattern contains a prefix, numeric part, and suffix, which allow
you to format a particular decimal value to the required precision and include leading
digits and commas as needed. The symbols used to build patterns are displayed in
Table 4-3 . Each of the patterns also contains a positive and negative subpattern. These
two subpatterns are separated by a semicolon ( ; ) and the negative subpattern is option-
al. If there is no negative subpattern present, the localized minus sign is used. For in-
stance, a complete pattern example would be ###,##0.00;(###,##0.00) .
Table 4-3 . DecimalFormat Pattern Characters
Character
Description
#
Digit; blank if no digit is present
 
 
Search WWH ::




Custom Search