Convert string number to integer number

This question already has an answer here:

  • How do I convert a String to an int in Java? 30 answers

  • Use Wrapper Class.

    Examples are below

    int

    int a = Integer.parseInt("1"); // Outputs 1
    

    float

    float a = Float.parseFloat("1"); // Outputs 1.0
    

    double

    double a = Double.parseFloat("1"); // Outputs 1.0
    

    long

    long a = Long.parseLong("1"); // Outputs 1
    

    int one = Integer.parseInt("1");
    

    理想情况下,你也应该捕捉错误:

    int i;
    String s = "might not be a number";
    try {
       i = Integer.parseInt(s);
    } catch (NumberFormatException e) {
       //do something
    }
    

    Integer.parseInt这样做的。

    int foo = Integer.parseInt("1");
    
    链接地址: http://www.djcxy.com/p/20906.html

    上一篇: 无法将字符串转换为Java中的整数

    下一篇: 将字符串编号转换为整数