Java中的parseDouble导致NumberFormatException [英] parseDouble in Java results to NumberFormatException

查看:904
本文介绍了Java中的parseDouble导致NumberFormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从属性文件加载信息,我有以下代码:

I am trying to load info from a properties file and i have the following code:

anInt = Integer.parseInt(prop.getProperty("anInt"));
aDouble = Double.parseDouble(prop.getProperty("aDouble"));

虽然第一行工作正常,但第二行我尝试
到加载一个double变量会抛出一个 NumberFormatException 。具体的异常消息是:

and while the first line works just fine, the second one where i am trying to load a double variable throws a NumberFormatException. The specific exception message is:

Exception in thread "main" java.lang.NumberFormatException: For input string: "78,5"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:59)
at Assignment1.BaseStation.main(BaseStation.java:83)


推荐答案

如果要使用 Double.parseDouble()进行解析,则必须使用句点作为分隔符,而不是逗号。它在Double类的文档中说

You have to use a period as a delimiter, not comma if you want to parse using Double.parseDouble(). It says in documentation for the Double class that


FloatingPointLiteral ... [is]在Java的词汇结构部分中定义语言规范。

FloatingPointLiteral ... [is] as defined in the lexical structure sections of the of the Java Language Specification.

来自Java语言规范:

From Java Language Specification:


FloatingPointLiteral:

FloatingPointLiteral:


  • 数字。数字选择 ExponentPart 选择 FloatTypeSuffix 选择

  • 。 Digits ExponentPart opt FloatTypeSuffix opt

  • Digits ExponentPart FloatTypeSuffix opt

  • Digits ExponentPart opt FloatTypeSuffix

  • Digits . Digits opt ExponentPart opt FloatTypeSuffix opt
  • . Digits ExponentPart opt FloatTypeSuffix opt
  • Digits ExponentPart FloatTypeSuffix opt
  • Digits ExponentPart opt FloatTypeSuffix

如果你想采用语言环境考虑到,您可以使用 java.text.NumberFormat

If you want to take locale into consideration, you can use java.text.NumberFormat:

NumberFormat nf = NumberFormat.getInstance();
double number = nf.parse(myString).doubleValue();

这篇关于Java中的parseDouble导致NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆