Pit Digger Pit Digger - 1 year ago 59
Java Question

Converting a String that contains decimal to Long

I have following sample (link to ideone).

long lDurationMillis = 0;
lDurationMillis = Long.parseLong("30000.1");
System.out.print("Play Duration:" + lDurationMillis);

It throws an exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "30000.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at Main.main(Main.java:9)

But why it wont let me convert that number to a string directly ?I can convert number to integer and than convert to double . But is there any other way ?

Answer Source

The value 30000.1 is an invalid long value. You could parse the double value first:

lDurationMillis = (long)Double.parseDouble("30000.1");