String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
3)
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();
We can shorten to:
String numberAsString = "1234";
long number = new Long(numberAsString).longValue();
Or Just
long number = new Long("1234").longValue();
4) Using Decemal format :
String numberAsString = "1234";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
long number = decimalFormat.parse(numberAsString).longValue();
System.out.println("The number is: " + number);
} catch (ParseException e) {
System.out.println(numberAsString + " is not a valid number.");
}
Map map = new HashMap();
map.put("name", "John");
map.put("time", "9648512236521");
map.put("age", "25");
long time = Long.valueOf((String)map.get("time")).longValue() ;
int age = Integer.valueOf((String) map.get("aget")).intValue();
System.out.println(time);
System.out.println(age);
public class StringToLong {
public static void main (String[] args) {
// String s = "fred"; // do this if you want an exception
String s = "100";
try {
long l = Long.parseLong(s);
System.out.println("long l = " + l);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
8 回答
最好的方法是Long.valueOf(str),因为它依赖于Long.valueOf(long),它使用内部缓存使其更有效,因为如果需要,
Long
的缓存实例将从-128
包含到127
.由于auto-unboxing允许将包装类的实例转换为其对应的基本类型,因此代码将为:
请注意,如果提供的
String
与签名的long
不匹配,则前面的代码仍然可以抛出NumberFormatException
.一般来说,使用
Integer
,Boolean
,Long
等封装类的static
工厂方法valueOf(str)
是一个好习惯,因为大多数情况下,只要有可能使它们在内存占用方面更有效,它们就会重用实例 . 相应的parse
方法或构造函数 .摘自Effective Java
Item 1
由 Joshua Bloch 撰写:要将 String 转换为 Long (对象),请使用
Long.valueOf(String s).longValue();
见link
There are some way to convert string to Integer :
1)
2)
3)
We can shorten to:
Or Just
4) Using Decemal format :
Long.valueOf(String s) - 显然,如果您的代码可以使用,则必须注意防范非数字 .
如果您使用带有泛型的Map,则需要将值转换为String,然后尝试转换为Long . 以下是示例代码
对于那些切换到Kotlin只是使用
string.toLong()
这将在引擎盖下召唤
Long.parseLong(string)
使用Long.parseLong()