简体   繁体   中英

Passing long to Double.parseDouble

When I pass in a number like 100L to Double.parseDouble() I get a NumberFormatException. But 100L is a valid number.

EDIT: I do not get any error is if pass 100d or 100f. I only get it for 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. Drop the "L" and you should be fine.

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.)

From the 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.

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. To avoid any error, try using "100" instead of "100L".

I do not get any error is if pass 100d or 100f. I only get it for 100L?

parseDouble() calls valueOf() , which specifically looks for floating point representations.Since, d and f denote doubles and floats, everything works fine. But, you shouldn't specifiy the number explicitly as long. ( like 100L)


FYI,

NumberFormatException: http://www.ideone.com/DMpUN
Runs normally: http://www.ideone.com/QdxXY


100l in a "String" is not a valid number. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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