68

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 Answers8

180

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.

Cristian
  • 198,401
  • 62
  • 356
  • 264
  • Thank you. i got stuck on lg.getLong as per [link](http://developer.android.com/reference/java/lang/Long.html#getLong(java.lang.String)) –  Mar 30 '12 at 03:43
  • `getLong` returns a long from a system property. That's why it does not work as you expected. – Cristian Mar 30 '12 at 03:48
  • It is easy to make the mistake of assuming the input string is in the form you expect ; "90.77" will throw ParseException with this. So dont ignore the ParseException, but handle it for your use case – Alex Punnen Apr 23 '14 at 06:58
9

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
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
6

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);
thor
  • 21,418
  • 31
  • 87
  • 173
Bijay Dhital
  • 61
  • 1
  • 1
5
String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}
borchvm
  • 3,533
  • 16
  • 44
  • 45
2
import org.apache.commons.lang.math.NumberUtils;

This will handle null

NumberUtils.createLong(String)
Slyvain
  • 1,732
  • 3
  • 23
  • 27
2

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Kazem Maleki
  • 179
  • 3
  • 6
2

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
Lucifer
  • 29,392
  • 25
  • 90
  • 143
1

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.

fidazik
  • 423
  • 1
  • 5
  • 11