62

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);
John
  • 895
  • 3
  • 9
  • 25

8 Answers8

176

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
  • 191,931
  • 60
  • 351
  • 260
  • Thank you. i got stuck on lg.getLong as per [link](http://developer.android.com/reference/java/lang/Long.html#getLong(java.lang.String)) – John 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
  • 13,346
  • 3
  • 29
  • 49
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);
tinlyx
  • 18,900
  • 26
  • 81
  • 148
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
  • 2,729
  • 7
  • 34
  • 36
3

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
Lucifer
  • 28,605
  • 21
  • 86
  • 137
2
import org.apache.commons.lang.math.NumberUtils;

This will handle null

NumberUtils.createLong(String)
Slyvain
  • 1,666
  • 3
  • 22
  • 27
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
  • 385
  • 1
  • 4
  • 10
1

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");
Mogsdad
  • 40,814
  • 19
  • 140
  • 246
Kazem Maleki
  • 139
  • 3
  • 5