我想将我作为字符串获得的一些数字转换为双精度数,但这些数字不在美国标准语言环境中,而是在不同的语言环境中.我该怎么做?
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模板网!
上传进度侦听器未触发(Google 驱动器 API)Upload progress listener not fired (Google drive API)(上传进度侦听器未触发(Google 驱动器 API))
使用 Google Drive SDK 将文件保存在特定文件夹中Save file in specific folder with Google Drive SDK(使用 Google Drive SDK 将文件保存在特定文件夹中)
Google Drive Android API - 无效的 DriveId 和 Null ResourcGoogle Drive Android API - Invalid DriveId and Null ResourceId(Google Drive Android API - 无效的 DriveId 和 Null ResourceId)
谷歌驱动api服务账户查看上传文件到谷歌驱动使Google drive api services account view uploaded files to google drive using java(谷歌驱动api服务账户查看上传文件到谷歌驱动使用java
Google Drive 服务帐号返回 403 usageLimitsGoogle Drive service account returns 403 usageLimits(Google Drive 服务帐号返回 403 usageLimits)
com.google.api.client.json.jackson.JacksonFactory;Google Drcom.google.api.client.json.jackson.JacksonFactory; missing in Google Drive example(com.google.api.client.json.jackson.JacksonFactory;Google Drive 示例