检查数字是否是Java中的整数

是否有任何方法或快速方法来检查数字是否是Java中的整数(属于Z字段)?

我想可能会从四舍五入的数字中减去它,但我没有找到任何可以帮助我的方法。

我应该在哪里检查? 整数Api?

又快又脏……

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

编辑:这是假设x已经是其他数字forms。 如果您正在处理字符串,请查看Integer.parseInt

一个例子更多:)

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

在这个例子中,可以使用ceil并具有完全相同的效果。

如果你在谈论浮点值,你必须非常小心,因为格式的性质。

我知道这样做的最好方法是决定一些epsilon值,比如0.000001f,然后做这样的事情:

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

然后

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

基本上你要检查z和z的整数情况是否在一定容差范围内具有相同的幅度。 这是必要的,因为浮动本质上是不精确的。

注意,但是:如果您的浮点数的大小大于Integer.MAX_VALUE (2147483647),这可能会中断,您应该意识到,必须不可能检查高于该值的浮点数的整数。

ZI假设你的意思是整数,即3,-5,77而不是3.14,4.02等。

正则表达式可能有所帮助:

 Pattern isInteger = Pattern.compile("\\d+"); 
  if((number%1)!=0) { System.out.println("not a integer"); } else { System.out.println("integer"); } 
  int x = 3; if(ceil(x) == x) { System.out.println("x is an integer"); } else { System.out.println("x is not an integer"); } 

将x更改为1并输出为整数,否则不是整数添加到计数示例整数,十进制数等。

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

//用C语言..但算法是一样的

 #include  int main(){ float x = 77.6; if(x-(int) x>0) printf("True! it is float."); else printf("False! not float."); return 0; }