How to convert string to long [duplicate]

2019-01-31 16:51发布

问题:

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

回答1:

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.



回答2:

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


回答3:

String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}


回答4:

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


回答5:

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);


回答6:

import org.apache.commons.lang.math.NumberUtils;

This will handle null

NumberUtils.createLong(String)


回答7:

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.



回答8:

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");