我正在尝试从属性文件加载信息,并且我有以下代码:
anInt = Integer.parseInt(prop.getProperty("anInt"));
aDouble = Double.parseDouble(prop.getProperty("aDouble"));
虽然第一行工作得很好,但我正在尝试的第二行
加载双变量会抛出 NumberFormatException
。具体异常信息为:
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 类的文档中说
FloatingPointLiteral ... [is] as defined in the lexical structure sections of the of the Java Language Specification.
来自 Java 语言规范:
FloatingPointLiteral:
- Digits . Digits opt ExponentPart opt FloatTypeSuffix opt
- . Digits ExponentPart opt FloatTypeSuffix opt
- Digits ExponentPart FloatTypeSuffix opt
- Digits ExponentPart opt FloatTypeSuffix
如果你想考虑语言环境,你可以使用java.text.NumberFormat
:
NumberFormat nf = NumberFormat.getInstance();
double number = nf.parse(myString).doubleValue();
关于java - Java 中的 parseDouble 结果为 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8285982/