Locale Aware Number Formatting
Render numbers and currency per locale with NumberFormat so grouping and decimal conventions come from the locale, not hand-rolled strings.
Code
import java.text.NumberFormat;
import java.util.Locale;
public class PriceFormatter {
public static void main(String[] args) {
double price = 1234567.891;
for (Locale locale : new Locale[] {Locale.US, Locale.GERMANY, Locale.CHINA}) {
NumberFormat currency = NumberFormat.getCurrencyInstance(locale);
NumberFormat number = NumberFormat.getNumberInstance(locale);
System.out.printf(
"%s: %s / %s%n",
locale,
currency.format(price),
number.format(price));
}
// 限定位数:货币场景统一两位小数
NumberFormat capped = NumberFormat.getNumberInstance(Locale.US);
capped.setMaximumFractionDigits(2);
System.out.println("capped: " + capped.format(price));
}
}How it works
Locale Aware Number Formatting reduces to the class PriceFormatter and the function main.
The one repetition in this snippet is the loop for (Locale locale : new Locale[] {Locale.US, Locale.GERMANY, Locale.CHINA}).
Applying it
The demo output is labeled (capped:), so every printed line maps back to its originating operation.
Statements that matter
NumberFormat currency = NumberFormat.getCurrencyInstance(locale);
NumberFormat capped = NumberFormat.getNumberInstance(Locale.US);
NumberFormat number = NumberFormat.getNumberInstance(locale);
Interactive Tools for This Topic
Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- What does Locale Aware Number Formatting print when run?
- Execute the whole file; each printed line is prefixed with a label like `capped:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.