Checking if a number is an Integer in Java

后端 未结 11 555
生来不讨喜
生来不讨喜 2020-12-09 15:48

Is there any method or quick way to check whether a number is an Integer (belongs to Z field) in Java?

I thought of maybe subtracting it from the rounded number, but

11条回答
  •  佛祖请我去吃肉
    2020-12-09 16:27

        double x == 2.15;
    
        if(Math.floor(x) == x){
            System.out.println("an integer");
        } else{
            System.out.println("not an integer");
        }
    

    I think you can similarly use the Math.ceil() method to verify whether x is an integer or not. This works because Math.ceil or Math.floor rounds up x to the nearest integer (say y) and if x==y then our original `x' was an integer.

提交回复
热议问题