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 07:20

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+");
查看更多
看我几分像从前
3楼-- · 2020-02-09 07:21

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.

查看更多
手持菜刀,她持情操
4楼-- · 2020-02-09 07:23

// 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;
}
查看更多
唯我独甜
5楼-- · 2020-02-09 07:24
/**
 * 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.
}
查看更多
登录 后发表回答