Customizing Decimal Number Formatting – Localization
By Gigi Rosen / December 24, 2022 / No Comments / Creating Resource Bundles, Oracle Certifications, The ZonedDateTime Class
Customizing Decimal Number Formatting
The java.text.DecimalFormat class formats and parses numbers (including BigDecimal) according to a string pattern, specified using special pattern symbols (Table 18.10) and taking into account any locale considerations. It can format numbers as integers (1234), fixed-point notation (3.14), scientific notation (2.99792458E8), percentages (60%), and currency amounts ($64.00).
Table 18.10 Selected Number Format Pattern Symbols for the United States
Pattern symbol | Purpose |
0 (Zero) | Placeholder for a digit. Can result in leading and/or trailing zeroes. Can result in rounding up of the fractional part of a number. |
# (Hash sign) | Placeholder for a digit. Leading and/or trailing zeroes may be absent. Can result in rounding up of the fractional part of a number. |
. (Dot) | Placeholder for decimal separator. If omitted, a floating-point number is rounded up to the nearest integer. Can be different for other countries. For example, in Germany, the decimal separator is the comma (,). |
, (Comma) | Placeholder for grouping separator (a.k.a. thousands separator). Can be different for other countries. For example, in Germany, the grouping separator is the period (.). |
Although the DecimalFormat class defines constructors, the Java API recommends using the factory methods of its abstract superclass NumberFormat to create an instance of this class.
NumberFormat df = NumberFormat.getNumberInstance(Locale.US);
if (nf intanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) nf;
df.applyPattern(pattern); // Supply the pattern.
String output = df.format(number); // Format the number.
}
The idiom is to create a DecimalFormat object as shown above, localized if necessary, and customizing it with a pattern using the method shown below. The overloaded format() methods inherited by the DecimalFormat class from its superclass Number-Format can now be called to format a number. The pattern can also be changed on the fly.
void applyPattern(String pattern)
Applies the given pattern to this DecimalFormat object.
Example 18.6 shows formatting of a number, either a double at (1a) or a BigDecimal at (1b), using different patterns at (2) and different locales at (3). Decimal formatters are created at (4), as explained above. A decimal formatter is customized with a pattern at (5) and the number is formatted at (6). In particular, note how the decimal and group separators are localized for each locale. The currency amounts are also formatted according to the particulars of each locale, and not according to the currency symbol that is specified in the currency patterns.
Example 18.6 Using the DecimalFormat class
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FormattingDecimalNumbers {
public static void main(String[] args) {
// The number to format.
double number = 1234.567; // (1a)
// BigDecimal number = new BigDecimal(“1234.567”); // (1b)
// Formats to use:
String[] patterns = { // (2)
“#”,
“###,###.##”,
“###.##”,
“00000.00”,
“BTC ###,###.##”, // BTC: Bitcoin
};
// Locales to consider:
Locale[] locales = { Locale.US, Locale.GERMANY }; // (3)
// Create localized DecimalFormats: (4)
List<DecimalFormat> dfs = new ArrayList<>(locales.length);
for (int i = 0; i < locales.length; i++) {
NumberFormat nf = NumberFormat.getNumberInstance(locales[i]);
if (nf instanceof DecimalFormat) {
dfs.add((DecimalFormat) nf);
}
}
// Write the header:
System.out.printf(“%15s”, “Patterns”);
for (Locale locale : locales) {
System.out.printf(“%15s”, locale);
}
System.out.println();
// Do formatting and print results:
for (String pattern : patterns) {
System.out.printf(“%15s”, pattern);
for (DecimalFormat df : dfs) {
df.applyPattern(pattern); // (5)
String output = df.format(number); // (6)
System.out.printf(“%15s”, output);
}
System.out.println();
}
}
}
Output from the program:
Patterns en_US de_DE
# 1235 1235
###,###.## 1,234.57 1.234,57
###.## 1234.57 1234,57
00000.00 01234.57 01234,57
BTC ###,###.## BTC 1,234.57 BTC 1.234,57