Checking if a number is an Integer in Java

2020-02-09 06:19发布

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 I didn't find any method that will help me with this.

Where should I check? Integer Api?

10条回答
趁早两清
2楼-- · 2020-02-09 06:59
    if((number%1)!=0)
    {
        System.out.println("not a integer");
    }
    else
    {
        System.out.println("integer");
    }
查看更多
Ridiculous、
3楼-- · 2020-02-09 07:03
 int x = 3;

 if(ceil(x) == x) {

  System.out.println("x is an integer");

 } else {

  System.out.println("x is not an integer");

 }
查看更多
等我变得足够好
4楼-- · 2020-02-09 07:04

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.

查看更多
够拽才男人
5楼-- · 2020-02-09 07:10

change x to 1 and output is integer, else its not an integer add to count example whole numbers, decimal numbers etc.

   double x = 1.1;
   int count = 0;
   if (x == (int)x)
    {
       System.out.println("X is an integer: " + x);
       count++; 
       System.out.println("This has been added to the count " + count);
    }else
   {
       System.out.println("X is not an integer: " + x);
       System.out.println("This has not been added to the count " + count);


   }
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-09 07:11

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.

查看更多
萌系小妹纸
7楼-- · 2020-02-09 07:18

Check if ceil function and floor function returns the same value

static boolean isInteger(int n) 
{ 
return (int)(Math.ceil(n)) == (int)(Math.floor(n)); 
} 
查看更多
登录 后发表回答