How to convert string to long

233,342

Solution 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.

Solution 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

Solution 3

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

Solution 4

String s = "1";

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

Solution 5

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
Share:
233,342
John
Author by

John

Computers are fun.

Updated on July 05, 2022

Comments

  • John
    John almost 2 years

    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);
    
  • Admin
    Admin about 12 years
    Thank you. i got stuck on lg.getLong as per link
  • Cristian
    Cristian about 12 years
    getLong returns a long from a system property. That's why it does not work as you expected.
  • Alex Punnen
    Alex Punnen about 10 years
    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
  • Debosmit Ray
    Debosmit Ray about 8 years
    Could you also add why you think this is better than simply calling parseLong()?