Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a value is of type Integer?

Tags:

java

integer

I need to check if a value is an integer. I found this: How to check whether input value is integer or float?, but if I'm not mistaken, the variable there is still of type double even though the value itself is indeed an integer.

like image 817
Voldemort Avatar asked Sep 24 '12 02:09

Voldemort


People also ask

How can I check if a value is of type integer Python?

To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.

How do you check if a value is a string or integer?

We can use the isdigit() function to check if the string is an integer or not in Python. The isdigit() method returns True if all characters in a string are digits. Otherwise, it returns False.


2 Answers

If input value can be in numeric form other than integer , check by

if (x == (int)x) {    // Number is integer } 

If string value is being passed , use Integer.parseInt(string_var). Please ensure error handling using try catch in case conversion fails.

like image 183
Mudassir Hasan Avatar answered Sep 23 '22 05:09

Mudassir Hasan


If you have a double/float/floating point number and want to see if it's an integer.

public boolean isDoubleInt(double d) {     //select a "tolerance range" for being an integer     double TOLERANCE = 1E-5;     //do not use (int)d, due to weird floating point conversions!     return Math.abs(Math.floor(d) - d) < TOLERANCE; } 

If you have a string and want to see if it's an integer. Preferably, don't throw out the Integer.valueOf() result:

public boolean isStringInt(String s) {     try     {         Integer.parseInt(s);         return true;     } catch (NumberFormatException ex)     {         return false;     } } 

If you want to see if something is an Integer object (and hence wraps an int):

public boolean isObjectInteger(Object o) {     return o instanceof Integer; } 
like image 43
Ryan Amos Avatar answered Sep 21 '22 05:09

Ryan Amos