Integer.parse(String str) java.lang.NumberFormatException: Errors

前端 未结 8 1580
一整个雨季
一整个雨季 2020-12-11 22:18

I keep getting number format expectations, even though I\'m trimming the strings and they don\'t contain non numerical characters bizarrely it works for some numbers and not

相关标签:
8条回答
  • 2020-12-11 22:56

    You could use

    String n="3020857508";
    Long a = Long.valueOf(n.trim()).longValue();
    System.out.println(a);
    
    0 讨论(0)
  • 2020-12-11 22:56

    Just like what @Codebender said. Your value is out of range for int. Try using long/Long instead.

    0 讨论(0)
  • 2020-12-11 22:57

    MAX_INT is 2147483647 and you're trying to parse a bigger number as Integer.

    You can use Long.parseLong instead:

    System.out.println(Long.parseLong("3020857508")); // 3020857508
    
    0 讨论(0)
  • 2020-12-11 23:00

    It's because 3020857508 exceeds Integer.MAX_VALUE. You should use long to convert the string to number.

    java> String n="3020857508";
    //=> java.lang.String n = "3020857508"
    java> Integer a = Integer.parseInt(n.trim());
    //=> java.lang.NumberFormatException: For input string: "3020857508"
    java> Integer.MAX_VALUE
    //=> java.lang.Integer res2 = 2147483647
    java> Long a = Long.parseLong(n.trim());
    //=>java.lang.Long a = 3020857508
    

    The above is javarepl output.

    If you are using JDK9 or above, you can see the same result in jshell.

    jshell> String n="3020857508"
    n ==> "3020857508"
    
    jshell> Integer a = Integer.parseInt(n.trim())
    |  Exception java.lang.NumberFormatException: For input string: "3020857508"
    |        at NumberFormatException.forInputString (NumberFormatException.java:65)
    |        at Integer.parseInt (Integer.java:652)
    |        at Integer.parseInt (Integer.java:770)
    |        at (#2:1)
    
    jshell> Integer.MAX_VALUE
    $3 ==> 2147483647
    
    jshell> Long a = Long.parseLong(n.trim());
    a ==> 3020857508
    
    0 讨论(0)
  • 2020-12-11 23:06

    The largest number parseable as an int is 2147483647 (231-1), and the largest long is 9223372036854775807 (263-1), only about twice as long.

    To parse arbitrarily long numbers, use:

    import java.math.BigInteger;
    
    BigInteger number = new BigInteger(str);
    
    0 讨论(0)
  • 2020-12-11 23:08

    The number you're trying to parse is larger than the max value of an Integer, you would have to use a larger data type like Long.

    public static void main(String[] args) {
        System.out.println("Integer max value: " + Integer.MAX_VALUE);
        System.out.println("Long max value: " + Long.MAX_VALUE);
        System.out.println();
    
        String n = "3020857508";
        Long a = Long.parseLong(n.trim());
        System.out.println(a);
    }
    

    Results:

    Integer max value: 2147483647
    Long max value: 9223372036854775807
    
    3020857508
    
    0 讨论(0)
提交回复
热议问题