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
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+");
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));
}
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.
// 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;
}
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);
}