如何检查值是否为Integer类型?

Vol*_*ort 47 java integer

我需要检查一个值是否为整数.我发现了这个:如何检查输入值是整数还是浮点数?,但是如果我没有弄错的话,变量仍然是类型,double即使本身确实是一个integer.

Mud*_*san 81

如果输入值可以是整数以外的数字形式,请检查

if (x == (int)x)
{
   // Number is integer
}
Run Code Online (Sandbox Code Playgroud)

如果正在传递字符串值,Integer.parseInt(string_var). 请使用请确保在转换失败的情况下使用try catch进行错误处理.

  • *ahem*try/catch parseint. (12认同)

Rya*_*mos 18

如果你有一个双/浮点/浮点数,并想看看它是否是一个整数.

public boolean isDoubleInt(double d)
{
    //select a "tolerance range" for being an integer
    double TOLERANCE = 1E-5;
    //do not use (int)d, due to weird floating point conversions!
    return Math.abs(Math.floor(d) - d) < TOLERANCE;
}
Run Code Online (Sandbox Code Playgroud)

如果你有一个字符串,并想看看它是否是一个整数.最好不要丢弃Integer.valueOf()结果:

public boolean isStringInt(String s)
{
    try
    {
        Integer.parseInt(s);
        return true;
    } catch (NumberFormatException ex)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想看看某个东西是否是一个Integer对象(并因此包装int):

public boolean isObjectInteger(Object o)
{
    return o instanceof Integer;
}
Run Code Online (Sandbox Code Playgroud)


Psh*_*emo 8

也许这样试试吧

try{
    double d= Double.valueOf(someString);
    if (d==(int)d){
        System.out.println("integer"+(int)d);
    }else{
        System.out.println("double"+d);
    }
}catch(Exception e){
    System.out.println("not number");
}
Run Code Online (Sandbox Code Playgroud)

但是整数范围之外的所有数字(如"-1231231231231231238")将被视为双打.如果你想摆脱这个问题,你可以这样试试

try {
    double d = Double.valueOf(someString);
    if (someString.matches("\\-?\\d+")){//optional minus and at least one digit
        System.out.println("integer" + d);
    } else {
        System.out.println("double" + d);
    }
} catch (Exception e) {
    System.out.println("not number");
}
Run Code Online (Sandbox Code Playgroud)


And*_*fii 8

您应该使用instanceof运算符来确定您的值是否为Integer;

Object object = your_value;

if(object instanceof Integer) {

Integer integer = (Integer) object ;

} else {
 //your value isn't integer
}
Run Code Online (Sandbox Code Playgroud)


Yas*_*ary 5

这是检查字符串是否为整数的函数?

public static boolean isStringInteger(String number ){
    try{
        Integer.parseInt(number);
    }catch(Exception e ){
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)


Gay*_*tti 5

if (x % 1 == 0)
    // x is an integer
Run Code Online (Sandbox Code Playgroud)

Here x is a numeric primitive: short, int, long, float or double