Number Formatting
java.util.Locale
A Locale object represents a specific geographical, political, or cultural region.
An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user.
For example, displaying a number is a locale-sensitive operation: Numbers should be formatted according to the customs and conventions of the user's native country, region, or culture.
Locale
properties -
Language
-
Encoding
-
Country
-
Extensible
NumberFormat
instance final NumberFormat standard = new DecimalFormat(); System.out.println(standard.format(1234.5678)); final NumberFormat de = DecimalFormat.getInstance(Locale.GERMANY); System.out.println(de.format(1234.5678)); |
1234.5678 1.234,568 |
final DecimalFormatSymbols unusualSymbols =
new DecimalFormatSymbols(Locale.getDefault());
unusualSymbols.setDecimalSeparator('|');
unusualSymbols.setGroupingSeparator('^');
final String strange = "#,##0.###";
final DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);
weirdFormatter.setGroupingSize(4);
System.out.println(weirdFormatter.format(12345.678));
1^2345|678
No. 176
Locale
definitions
Q: |
Each JRE™ ships with a set of available
160 locales available: Locale: Arabic(ar_AE) Locale: Arabic(ar_JO) Locale: Arabic(ar_SY) Locale: Croatian(hr_HR) ... Locale: Indonesian(in_ID) Locale: English(en_GB) TipRead the documentation of |
A: |
|
No. 177
Formatting int
, double
and LocaleDate
Q: |
Implement the following three overloaded class methods:
You may use them as:
The expected output reads: Locale Germany 1.234.567 -123,457 22. Dezember 2024 ---------------------- Locale Japan 1,234,567 -123.457 2024/12/22 ---------------------- Locale United States 1,234,567 -123.457 December 22, 2024 ---------------------- Tip
|
A: |
Implementing the first two methods is relatively simple:
Processing dates is a bit cumbersome:
|
final NumberFormat de = NumberFormat.getInstance(Locale.GERMANY),
us = NumberFormat.getInstance(Locale.US);
try {
final Number[] values = {
de.parse("103.234"), de.parse("400.000,234"),
us.parse("103.234"), us.parse("400.000,234"),};
for (final Number n: values) {
System.out.println(n + "(" + n.getClass().getTypeName() + ")");
} catch (ParseException e) { ... }
103234(java.lang.Long) 400000.234(java.lang.Double) 103.234(java.lang.Double) 400(java.lang.Long)