← 中文资源

简体中文版本

NumberFormat 本地化解析往返

同一 Locale 内 format 产出文本、parse 精确还原数值;跨 locale 解析时分隔符语义不同,1.234.567,891 被 US locale 读成 1.234(第一个 '.' 当小数点,第二个 '.' 处停止解析),setParseIntegerOnly 同样在小数点截停。

阅读英文原文

实现说明

全部逻辑都在类 AmountRoundtrip中。

使用要点

  • 每一步打印都带着自己的标签:de text:、de back:、us reads de text as:。

常见问题

运行「NumberFormat 本地化解析往返」会打印什么?

运行文件本身,de text:、de back:、us reads de text as: 这些前缀各对应一段演示逻辑。

核心语句

NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
NumberFormat us = NumberFormat.getNumberInstance(Locale.US);
double deBack = de.parse(deText).doubleValue();

代码示例

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class AmountRoundtrip {

    public static void main(String[] args) throws ParseException {
        double amount = 1234567.891;

        // 同一 locale 内往返:format 产出文本,parse 还原数值
        NumberFormat de = NumberFormat.getNumberInstance(Locale.GERMANY);
        String deText = de.format(amount);
        double deBack = de.parse(deText).doubleValue();
        System.out.println("de text:  " + deText);
        System.out.println("de back:  " + deBack + " equal: " + (deBack == amount));

        // 换 locale 解析别家的文本:分组符语义不同,结果被截断
        NumberFormat us = NumberFormat.getNumberInstance(Locale.US);
        double usRead = us.parse(deText).doubleValue();
        System.out.println("us reads de text as: " + usRead);

        // setParseIntegerOnly:解析在小数点停下,尾部文本被忽略
        us.setParseIntegerOnly(true);
        System.out.println("integer only: " + us.parse("3.99 extra"));
    }
}