开发者

Passing long to Double.parseDouble

开发者 https://www.devze.com 2023-03-19 13:02 出处:网络
When I pass in a number like 100L to Double.parseDouble() I get a 开发者_StackOverflow中文版NumberFormatException.

When I pass in a number like 100L to Double.parseDouble() I get a 开发者_StackOverflow中文版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.

0

精彩评论

暂无评论...
验证码 换一张
取 消