How to convert string to long [duplicate]

╄→гoц情女王★ 提交于 2019-11-28 18:20:00

问题


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:


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



回答4:


String s = "1";

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



回答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");


来源:https://stackoverflow.com/questions/9936648/how-to-convert-string-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!