如何使用特定的语言环境在Java中将String转换为Double? [英] How do I convert a String to Double in Java using a specific locale?
问题描述
我想将我得到的一些数字转换为双打,但这些数字不是美国标准语言环境,而是另一个。我怎么能这样做?
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:
要为不同的Locale格式化数字,请在对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()
返回 Number
;所以要获得 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
的通用实例(根据Javadocs 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!
这篇关于如何使用特定的语言环境在Java中将String转换为Double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!