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.

JavaData Integrity

Code

snippet
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

FAQ

What does Locale Aware Number Formatting print when run?
Execute the whole file; each printed line is prefixed with a label like `capped:`.