This question already has an answer here:
-
How to convert String to long in Java?
8 answers
how do you convert a string into a long.
for int you
int i = 3423;
String str;
str = str.valueOf(i);
so how do you go the other way but with long.
long lg;
String Str = "1333073704000"
lg = lg.valueOf(Str);
This is a common way to do it:
long l = Long.parseLong(str);
There is also this method: Long.valueOf(str);
Difference is that parseLong
returns a primitive long
while valueOf
returns a new Long()
object.
The method for converting a string to a long is Long.parseLong. Modifying your example:
String s = "1333073704000";
long l = Long.parseLong(s);
// Now l = 1333073704000
String s = "1";
try {
long l = Long.parseLong(s);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
IF your input is String then I recommend you to store the String into a double and then convert the double to the long.
String str = "123.45";
Double a = Double.parseDouble(str);
long b = Math.round(a);
You can also try following,
long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
import org.apache.commons.lang.math.NumberUtils;
This will handle null
NumberUtils.createLong(String)
Do this:
long l = Long.parseLong(str);
However, always check that str contains digits to prevent throwing exceptions.
For instance:
String str="ABCDE";
long l = Long.parseLong(str);
would throw an exception but this
String str="1234567";
long l = Long.parseLong(str);
won't.
Use parseLong()
, e.g.:
long lg = lg.parseLong("123456789123456789");