Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NumberFormatException for converting string to long [closed]

I am trying to convert a string to long and it throws the NumberFormatException. I don't think it is beyond range of long at all.

Here is the code to convert, where count_strng is the String I want to convert to long. trim() function is not making any difference.

long sum_link = Long.parseLong(count_strng.trim());

Here is the stacktrace.

java.lang.NumberFormatException: For input string: "0.003846153846153846"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)

Anyone knows what is the exact issue here?

like image 309
Keval Shah Avatar asked Oct 16 '15 17:10

Keval Shah


People also ask

What does NumberFormatException do in Java?

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float).

Can we convert string to long in Java?

We can convert String to long in java using Long. parseLong() method.

How do I fix NumberFormatException?

NumberFormatException and how to solve them. It's one of those errors where you need to investigate more about data than code. You need to find the source of invalid data and correct it. In code, just make sure you catch the NumberFormatException whenever you convert a string to a number in Java.

What is Java Lang NumberFormatException null?

NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer. parseInt() which convert String to int, Double.


2 Answers

Long.parseLong() is trying to parse the input string into a long. In Java, a long is defined such that:

The long data type is a 64-bit two's complement integer.

An integer is defined such that:

An integer (from the Latin integer meaning "whole") is a number that can be written without a fractional component.

The error you are getting shows the input string you are trying to parse is "0.003846153846153846", which clearly does have a fractional component.

You should use Double.parseDouble() if you want to parse a floating point number.

like image 129
azurefrog Avatar answered Oct 20 '22 04:10

azurefrog


As your input string is actually not a long, parsing into long would throw NumberFormatException. Rather try this

Double d = Double.parseDouble(count_strng.trim());
Long l = d.longValue();
like image 9
SacJn Avatar answered Oct 20 '22 02:10

SacJn