|
|
Number and Currency Formatting |
You can use theDecimalFormatclass 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. If you want to change formatting symbols such as the decimal separator, you can use theDecimalFormatSymbolsin conjunction with theDecimalFormatclass. These classes offer a great deal of flexibility in the formatting of numbers, but they can make your code more complex. Whenever possible, you should use theNumberFormatclass, which is described in the previous section, instead ofDecimalFormatandDecimalFormatSymbols.Using examples, the text that follows shows you how to use the
DecimalFormatandDecimalFormatSymbolsclasses. The code examples in this material are from a sample program called DecimalFormatDemo.java.Constructing Patterns
You specify the formatting properties ofDecimalFormatwith a a patternString. The pattern determines what the formatted number looks like. For a full description of the pattern syntax, see Number Format Pattern Syntax.In the example that follows, we create a formatter by passing a pattern
Stringto theDecimalFormatconstructor. Then, we pass adoublevalue to theformatmethod, which returns a formattedString:The output for the preceeding lines of code is described in the following table. TheDecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(value + " " + pattern + " " + output);valueis the number, adouble, that is to be formatted. Thepatternis theStringthat specifies the formatting properties. Theoutput, which is aString, represents the formatted number.
value pattern output Explanation 123456.789 ###,###.### 123,456.789 The pound sign (#) denotes a digit, the comma is a placeholder
for the grouping separator, and the period is a placeholder
for the decimal separator.123456.789 ###.## 123456.79 The valuehas three digits to the right of the decimal
point, but thepatternhas only two. Theformatmethod
handles this by rounding up.123.78 000000.000 000123.780 The patternspecifies leading and trailing zeros, because the
zero character is used instead of the pound sign (#).12345.67 $###,###.### $12,345.67 The first character in the patternis the dollar sign ($).
Note that the dollar sign immediately preceeds the left-most digit
in the formattedoutput.12345.67 \u00a5###,###.### ¥12,345.67 The patternspecifies the currency sign for Japanese yen (¥)
with the Unicode value \u00a5.Locale-sensitive Formatting
The preceeding example created aDecimalFormatobject for the defaultLocale. If you want aDecimalFormatobject for a non-defaultLocale, you instantiate aNumberFormatand then cast it toDecimalFormat. Then, theDecimalFormatobject will format the patterns you define in a locale-sensitive manner. Here's an example:Running the preceeding code example results in the output that follows. The formatted number, in the second column, varies withNumberFormat nf = NumberFormat.getNumberInstance(loc); DecimalFormat df = (DecimalFormat)nf; df.applyPattern(pattern); String output = df.format(value); System.out.println(pattern + " " + output + " " + loc.toString());Locale:So far, the formatting patterns we've shown you follow the conventions of U.S. English. For example, in the pattern "###,###.##" the comma is the thousands-separator and the period represents the decimal point. This convention is fine, provided that your end-users aren't exposed to it. However, some applications, like spreadsheets and report generators, allow the end-users to define their own formatting patterns. For these applications, the formatting patterns specified by the end-users should use localized notation. In these cases, you'll want to invoke the###,###.### 123,456.789 en_US ###,###.### 123.456,789 de_DE ###,###.### 123 456,789 fr_FRapplyLocalizedPatternmethod upon theDecimalFormatobject.Altering the Formatting Symbols
With the DecimalFormatSymbolsclass you can change the symbols that appear in the formatted numbers produced by the
formatmethod. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others.In the example that follows, we illustrate the use of
DecimalFormatSymbolsby applying an unusual format to a number. We start by instantiatingDecimalFormatSymbolswithout any arguments, which returns an object for the defaultLocale. (BecauseDecimalFormatSymbolsis a locale-sensitive class, we could have specified aLocalewhen invoking the constructor.) Next, we modify the decimal and grouping separators. Then we specify theDecimalFormatSymbolswhen instantiating theDecimalFormatclass. Just to make things more complicated, we change the grouping size of the formatter from three to four. Finally, we invoke theformatmethod.Here is the example code:
This is what appears when we print this bizarrely formatted number:DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(); unusualSymbols.setDecimalSeparator('|'); unusualSymbols.setGroupingSeparator('^'); String strange = "#,##0.###"; DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); weirdFormatter.setGroupingSize(4); String bizarre = weirdFormatter.format(12345.678); System.out.println(bizarre);1^2345|678
|
|
Number and Currency Formatting |