問題描述
我想將我作為字符串獲得的一些數字轉換為雙精度數,但這些數字不在美國標準語言環境中,而是在不同的語言環境中.我該怎么做?
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!
這篇關于如何使用特定語言環境在 Java 中將 String 轉換為 Double?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!