Checking if a number is an Integer in Java

后端 未结 11 494
生来不讨喜
生来不讨喜 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:09
        if((number%1)!=0)
        {
            System.out.println("not a integer");
        }
        else
        {
            System.out.println("integer");
        }
    
    0 讨论(0)
  • 2020-12-09 16:10
     int x = 3;
    
     if(ceil(x) == x) {
    
      System.out.println("x is an integer");
    
     } else {
    
      System.out.println("x is not an integer");
    
     }
    
    0 讨论(0)
  • 2020-12-09 16:12

    One example more :)

    double a = 1.00
    
    if(floor(a) == a) {
       // a is an integer
    } else {
       //a is not an integer.
    }
    

    In this example, ceil can be used and have the exact same effect.

    0 讨论(0)
  • 2020-12-09 16:13

    Quick and dirty...

    if (x == (int)x)
    {
       ...
    }
    

    edit: This is assuming x is already in some other numeric form. If you're dealing with strings, look into Integer.parseInt.

    0 讨论(0)
  • 2020-12-09 16:19

    if you're talking floating point values, you have to be very careful due to the nature of the format.

    the best way that i know of doing this is deciding on some epsilon value, say, 0.000001f, and then doing something like this:

    boolean nearZero(float f)
    {
        return ((-episilon < f) && (f <epsilon)); 
    }
    

    then

    if(nearZero(z-(int)z))
    { 
        //do stuff
    }
    

    essentially you're checking to see if z and the integer case of z have the same magnitude within some tolerance. This is necessary because floating are inherently imprecise.

    NOTE, HOWEVER: this will probably break if your floats have magnitude greater than Integer.MAX_VALUE (2147483647), and you should be aware that it is by necessity impossible to check for integral-ness on floats above that value.

    0 讨论(0)
  • 2020-12-09 16:20
    /**
     * Check if the passed argument is an integer value.
     *
     * @param number double
     * @return true if the passed argument is an integer value.
     */
    boolean isInteger(double number) {
        return number % 1 == 0;// if the modulus(remainder of the division) of the argument(number) with 1 is 0 then return true otherwise false.
    }
    
    0 讨论(0)
提交回复
热议问题