45

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Unknown user
  • 44,551
  • 16
  • 38
  • 42

13 Answers13

77

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.

Bleaourgh
  • 1,276
  • 9
  • 3
  • 1
    Normally I have a function isInteger(), which has try catch over Integer.parseInt, returning false in case exception is occurring. – Serhiy Mar 31 '11 at 15:49
  • 1
    this is a good answer, and I upvoted it for that reason -- but still, make sure you understand the limitations of floating point representations! – Alexander Questioning Bresee Mar 31 '11 at 16:03
  • orginaly this solution dont work for me but it use it in this wary: if (x.intValue() == x.doubleValue()) {} – taha May 19 '21 at 05:41
17

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.

evilone
  • 22,410
  • 7
  • 80
  • 107
10
/**
 * 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.
}
Dhananjay M
  • 1,851
  • 22
  • 18
4

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.

  • 1
    +1: You get round error on `float` for integers greater than 2^24 (about 16 million) If you use `double` you get round errors for integers gretaer than 2^53 (8 million trillion) – Peter Lawrey Mar 31 '11 at 16:43
1

With Z I assume you mean Integers , i.e 3,-5,77 not 3.14, 4.02 etc.

A regular expression may help:

Pattern isInteger = Pattern.compile("\\d+");
sthysel
  • 377
  • 3
  • 8
1
    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.

0

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);


   }
Community
  • 1
  • 1
0
    if((number%1)!=0)
    {
        System.out.println("not a integer");
    }
    else
    {
        System.out.println("integer");
    }
Learner
  • 449
  • 1
  • 7
  • 16
0
 int x = 3;

 if(ceil(x) == x) {

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

 } else {

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

 }
  • 1
    This pretty much repeats the top answers and without including the `ceil(int)` function, this is unusable. Also, if `x` is already an `int`, what point does this check even have? – randers May 08 '16 at 17:52
0

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)); 
} 
Shubham Chopra
  • 1,678
  • 17
  • 30
0

All given solutions are good, however most of them can give issues with Static Code Analysis (e.g. SONAR): "Floating point numbers should not be tested for equality" (see https://jira.sonarsource.com/browse/RSPEC-1244).

I am assuming that input that should be tested is double, not string.

As a workaround, I test numbers for not being integers:

public boolean isNotInteger(double x) {
    return x - Math.floor(x) > 0;
}
luca.vercelli
  • 898
  • 7
  • 24
-1

You can just use x % 1 == 0 because x % 1 gives the residual value of x / 1

D3crvpt3d
  • 7
  • 1
-3

// in C language.. but the algo is same

#include <stdio.h>

int main(){
  float x = 77.6;

  if(x-(int) x>0)
    printf("True! it is float.");
  else
    printf("False! not float.");        

  return 0;
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Probably you should post it in a question explicitly targeted at C (e.g. [1](https://stackoverflow.com/questions/5796983/checking-if-float-is-an-integer), [2](https://stackoverflow.com/questions/20068234/c-how-to-check-if-the-number-is-integer-or-float) )? Make sure that your approach doesn't repeat already posted answers. – default locale Feb 08 '17 at 11:13