简体   繁体   English

将 long 传递给 Double.parseDouble

[英]Passing long to Double.parseDouble

When I pass in a number like 100L to Double.parseDouble() I get a NumberFormatException.当我将 100L 之类的数字传递给 Double.parseDouble() 时,我得到一个 NumberFormatException。 But 100L is a valid number.但是 100L 是一个有效的数字。

EDIT: I do not get any error is if pass 100d or 100f.编辑:如果通过 100d 或 100f,我没有收到任何错误。 I only get it for 100L我只买了100L

100L is a literal that represents the long value 100. The string "100L" is not, so when you pass it to parseDouble() it rightfully complains. 100L 是一个表示长值 100 的文字。字符串“100L”不是,所以当你将它传递给 parseDouble() 时,它理所当然地抱怨。 Drop the "L" and you should be fine.去掉“L”,你应该没问题。

Update : It's not that parseDouble() doesn't like the literal syntax, it's that it doesn't like that you've explicitly declared the number as being a long (when in fact it's looking for a floating point type.)更新:不是parseDouble()不喜欢文字语法,而是它不喜欢你明确声明数字为long (实际上它正在寻找浮点类型。)

From the JavaDocs, Double.parseDouble();来自 JavaDocs, Double.parseDouble();

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

Syntax,句法,

public static double parseDouble(String s) throws NumberFormatException

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

It expects a string to be passed as argument.它期望一个字符串作为参数传递。 "100L" is a literal having value long, not a string. "100L" 是一个值 long 的文字,而不是字符串。 To avoid any error, try using "100" instead of "100L".为避免任何错误,请尝试使用“100”而不是“100L”。

I do not get any error is if pass 100d or 100f.如果通过 100d 或 100f,我没有收到任何错误。 I only get it for 100L?我只买100L?

parseDouble() calls valueOf() , which specifically looks for floating point representations.Since, d and f denote doubles and floats, everything works fine. parseDouble()调用valueOf() ,它专门寻找浮点表示。因为 d 和 f 表示双精度和浮点数,所以一切正常。 But, you shouldn't specifiy the number explicitly as long.但是,您不应该明确指定数字。 ( like 100L) (如100L)


FYI,供参考,

NumberFormatException: http://www.ideone.com/DMpUN NumberFormatException: http://www.ideone.com/DMpUN
Runs normally: http://www.ideone.com/QdxXY正常运行: http://www.ideone.com/QdxXY


100l in a "String" is not a valid number. “字符串”中的 100l 不是有效数字。 You simply need to pass in a valid double string.您只需要传入一个有效的双字符串。

class test{
    public static void main(String... args){
            System.out.println(Double.parseDouble("100.0000"));
    }}

This works fine.这工作正常。 As another user noted passing "100l" in the string wont work because the l implies the long value as a literal number.正如另一位用户指出的那样,在字符串中传递“100l”是行不通的,因为 l 意味着将 long 值作为文字数字。

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

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