← 中文资源

简体中文版本

Locale 感知的数字格式化

用 NumberFormat 按 Locale 渲染货币与数字:千分位与小数惯例来自区域设置,可用 setMaximumFractionDigits 收口。

阅读英文原文

实现说明

Locale 感知的数字格式化以类 PriceFormatter和函数 main为骨架。 for (Locale locale : new Locale[] {Locale.US, Locale.GERMANY, Locale.CHINA}) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 每一步打印都带着自己的标签:capped:。

常见问题

运行「Locale 感知的数字格式化」会打印什么?

运行文件本身,capped: 这些前缀各对应一段演示逻辑。

核心语句

NumberFormat currency = NumberFormat.getCurrencyInstance(locale);
NumberFormat capped = NumberFormat.getNumberInstance(Locale.US);
NumberFormat number = NumberFormat.getNumberInstance(locale);

代码示例

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));
    }
}