如何使用特定语言环境在 Java 中将 String 转换为 Double?

2022-01-11 00:00:00 localization java

我想将我作为字符串获得的一些数字转换为双精度数,但这些数字不在美国标准语言环境中,而是在不同的语言环境中.我该怎么做?

I want to convert some numbers which I got as strings into Doubles, but these numbers are not in US standard locale, but in a different one. How can I do that?

推荐答案

试试 java.text.NumberFormat.来自 Javadocs:

Try java.text.NumberFormat. From the Javadocs:

要为不同的区域设置格式化数字,请在调用 getInstance 时指定它.

To format a number for a different Locale, specify it in the call to getInstance.

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

您还可以使用 NumberFormat 来解析数字:

You can also use a NumberFormat to parse numbers:

myNumber = nf.parse(myString);

parse() 返回一个 编号;所以要获得一个double,你必须调用myNumber.doubleValue():

parse() returns a Number; so to get a double, you must call myNumber.doubleValue():

    double myNumber = nf.parse(myString).doubleValue();

请注意,parse() 永远不会返回 null,因此这不会导致 NullPointerException.相反,如果失败,parse 会抛出一个检查过的 ParseException.

Note that parse() will never return null, so this cannot cause a NullPointerException. Instead, parse throws a checked ParseException if it fails.

我最初说还有另一种方法可以转换为double:将结果转换为Double并使用拆箱.我认为由于使用了 NumberFormat 的通用实例(根据 getInstance),它总是返回一个 Double.但是 DJClayworth 指出 parse(String, ParsePosition)(由 parse(String) 调用)表示如果可能返回一个 Long.因此,将结果转换为 Double 是不安全的,不应尝试!
谢谢,DJClayworth!

I originally said that there was another way to convert to double: cast the result to Double and use unboxing. I thought that since a general-purpose instance of NumberFormat was being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworth points out that the Javadocs for parse(String, ParsePosition) (which is called by parse(String)) say that a Long is returned if possible. Therefore, casting the result to Double is unsafe and should not be tried!
Thanks, DJClayworth!

相关文章