Checking if a number is an Integer in Java

后端 未结 11 495
生来不讨喜
生来不讨喜 2020-12-09 15:48

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

相关标签:
11条回答
  • 2020-12-09 16:23

    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+");
    
    0 讨论(0)
  • 2020-12-09 16:23

    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)); 
    } 
    
    0 讨论(0)
  • 2020-12-09 16:27
        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 讨论(0)
  • 2020-12-09 16:30

    // 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;
    }
    
    0 讨论(0)
  • 2020-12-09 16:33

    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);
    
    
       }
    
    0 讨论(0)
提交回复
热议问题