我在Java中得到了一个简单的问题:如何将long . tostring()获得的字符串转换为长字符串?


当前回答

如果您使用的Map没有泛型,那么您需要将值转换为字符串,然后尝试转换为长。下面是示例代码

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

其他回答

有几种方法可以将String转换为long:

1)

long l = Long.parseLong("200"); 
String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();

我们可以缩短为:

String numberAsString = "1234";
long number = new Long(numberAsString).longValue();

或者只是

long number = new Long("1234").longValue();

使用十进制格式:

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.");
}

对于那些切换到Kotlin的人,只需使用 string.toLong () 这将在引擎盖下调用Long.parseLong(string)

首先,您需要检查字符串是否要转换为长 为避免出现NumberFormatException,它不是空的,并且是真正的Long。 要做到这一点,最好的方法是创建一个像这样的新方法:

    public static Long convertStringToLong(String str) {
        try {
            return Long.valueOf(str);
        } catch (NumberFormatException e) {
            return null;
        }
    }

这很简单,使用 长。返回对象的值(字符串);

例如:

String s;
long l;

Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);

你做完了! !

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

   }
}