简体   繁体   English

Double.parseDouble(“100d”)如何没有错误

[英]how does the Double.parseDouble(“100d”) gets no error

Double.parseDouble("100a"); // getting the error as expected But why does the below line doesn't gets the error //按预期获得错误但是为什么下面的行没有得到错误

Double.parseDouble("100d");

Please explain me. 请解释一下。

According to the source code, the Double.parseDouble(String s) method uses the FloatingDecimal.readJavaFormatString(String s) to parse the provided argument. 根据源代码, Double.parseDouble(String s)方法使用FloatingDecimal.readJavaFormatString(String s)来解析提供的参数。

There, you can see that there's a check if the provided String ends with 'D' , 'd' , 'F' or 'f' and if it doesn't, then a NumberFormatException is thrown: 在那里,你可以看到检查提供的String是否以'D''d''F''f'结尾,如果没有,则抛出NumberFormatException

if (i < l &&
   ((i != l - 1) ||
    (in.charAt(i) != 'f' &&
     in.charAt(i) != 'F' &&
     in.charAt(i) != 'd' &&
     in.charAt(i) != 'D'))) {
       break parseNumber; // go throw exception
     }

d represents double . d代表double

public static double parseDouble(String s) throws NumberFormatException

Throws:
NumberFormatException - if the string does not contain a parsable double.

100d is a parsable double string that's why it doesn't show any error. 100d是一个可解析的double字符串,这就是它没有显示任何错误的原因。

The javadoc says: javadoc说:

Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double. 返回一个初始化为由指定String表示的值的新double,由double类的valueOf方法执行。

So we look at the javadoc for Double::valueOf which gives the detailed acceptable syntax, in particular: 所以我们看一下Double::valueOf的javadoc,它给出了详细的可接受语法,特别是:

Sign opt FloatingPointLiteral 签署opt FloatingPointLiteral

where FloatingPointLiteral is as defined in the JLS. 其中FloatingPointLiteral在JLS中定义。 So we go to JLS #3.10.2 and you see that it can end with f , F , d or D , as expected. 所以我们转到JLS#3.10.2并且你看到它可以按照预期以fFdD结束。


If you want to only accept "human-readable doubles", you can use a DecimalFormat . 如果您只想接受“人类可读的双打”,则可以使用DecimalFormat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM