How to convert string to long [duplicate]

2019-01-31 16:23发布

This question already has an answer here:

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

8条回答
Bombasti
2楼-- · 2019-01-31 16:36

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
查看更多
Evening l夕情丶
3楼-- · 2019-01-31 16:39

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
查看更多
走好不送
4楼-- · 2019-01-31 16:43
import org.apache.commons.lang.math.NumberUtils;

This will handle null

NumberUtils.createLong(String)
查看更多
The star\"
5楼-- · 2019-01-31 16:47
String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}
查看更多
淡お忘
6楼-- · 2019-01-31 16:50

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.

查看更多
Fickle 薄情
7楼-- · 2019-01-31 16:55

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.

查看更多
登录 后发表回答