71

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.

Community
  • 1
  • 1
Saturn
  • 17,888
  • 49
  • 145
  • 271

12 Answers12

111

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.

Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
28

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;
}
Ryan Amos
  • 5,422
  • 4
  • 36
  • 56
  • 1
    Using == to compare doubles (as in your `isDoubleInt()` method) is dangerous because of loss of precision. Instead, you should do something like `Math.floor(d) - d < DELTA;` where `DELTA` is set to some very small value. – Code-Apprentice Sep 24 '12 at 03:54
  • 1
    Your code is wrong. It should be `< TOLERANCE` not `> TOLERANCE`. – andresp Jan 22 '17 at 17:30
  • @andresp Thanks! Fixed. – Ryan Amos Jan 23 '17 at 19:42
  • You are welcome. You are still missing a semi-colon after 1E-5, but that's easily noticed once you try to compile. – andresp Jan 24 '17 at 18:57
  • This answer is underrated. I'm using it to make an educated guess as to whether a double (Apache POI always treats numbers as doubles) was "intended" to be displayed as an integer so I can use Gson (which will look at my object representation, which I want to be Integer) to convert to JSON. – k-den Jun 30 '17 at 23:31
  • What will happen if `d = 0.999999`? – Toivo Säwén Feb 20 '20 at 10:14
  • Ultimately you have to choose a cutoff. Chose one that's reasonable, but test it thoroughly. Too large of a cutoff and you'll get false positives, too narrow and you'll get false negatives. That, or, use `BigDecimal` – Ryan Amos Mar 10 '20 at 00:18
21
if (x % 1 == 0)
    // x is an integer

Here x is a numeric primitive: short, int, long, float or double

Gayan Weerakutti
  • 11,904
  • 2
  • 71
  • 68
8

Try maybe this way

try{
    double d= Double.valueOf(someString);
    if (d==(int)d){
        System.out.println("integer"+(int)d);
    }else{
        System.out.println("double"+d);
    }
}catch(Exception e){
    System.out.println("not number");
}

But all numbers outside Integers range (like "-1231231231231231238") will be treated as doubles. If you want to get rid of that problem you can try it this way

try {
    double d = Double.valueOf(someString);
    if (someString.matches("\\-?\\d+")){//optional minus and at least one digit
        System.out.println("integer" + d);
    } else {
        System.out.println("double" + d);
    }
} catch (Exception e) {
    System.out.println("not number");
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • As Code-Guru pointed on on my answer, `d` may look like this: 47.000000001, due to loss of precision. You can never trust a double to be exact. Use range checking to solve this. – Ryan Amos Sep 24 '12 at 04:00
8

You should use the instanceof operator to determine if your value is Integer or not;

Object object = your_value;

if(object instanceof Integer) {

Integer integer = (Integer) object ;

} else {
 //your value isn't integer
}
Andrei Amarfii
  • 685
  • 1
  • 6
  • 17
5

Here is the function for to check is String is Integer or not ?

public static boolean isStringInteger(String number ){
    try{
        Integer.parseInt(number);
    }catch(Exception e ){
        return false;
    }
    return true;
}
Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31
1

This can work:

int no=0;
try
{
    no=Integer.parseInt(string);
    if(string.contains("."))
    {
        if(string.contains("f"))
        {
            System.out.println("float");
        }
        else
            System.out.println("double");
    }
}

catch(Exception ex)
{
    Console.WriteLine("not numeric or string");
}
osgx
  • 90,338
  • 53
  • 357
  • 513
Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70
1

To check if a String contains digit character which represent an integer, you can use Integer.parseInt().

To check if a double contains a value which can be an integer, you can use Math.floor() or Math.ceil().

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
1

You need to first check if it's a number. If so you can use the Math.Round method. If the result and the original value are equal then it's an integer.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Amjad Abdelrahman
  • 3,372
  • 1
  • 13
  • 20
1

this is the shortest way I know with negative integers enabled:

Object myObject = "-1";

if(Pattern.matches("\\-?\\d+", (CharSequence) myObject);)==true)
{
    System.out.println("It's an integer!");
}

And this is the way with negative integers disabled:

Object myObject = "1";

if(Pattern.matches("\\d+", (CharSequence) myObject);)==true)
{
    System.out.println("It's an integer!");
}
august0490
  • 777
  • 1
  • 9
  • 15
1

Try this snippet of code

private static boolean isStringInt(String s){
    Scanner in=new Scanner(s);
    return in.hasNextInt();
}
0

You can use modulus %, the solution is so simple:

import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter first number");
    Double m = scan.nextDouble();
    System.out.println("Enter second number");
    Double n= scan.nextDouble();

    if(m%n==0) 
    {
        System.out.println("Integer");
    }
    else
    {
        System.out.println("Double");
    }


}
}
Ali.Ghodrat
  • 3,348
  • 3
  • 31
  • 31