209

Is it possible to do this?

double variable;
variable = 5;
/* the below should return true, since 5 is an int. 
if variable were to equal 5.7, then it would return false. */
if(variable == int) {
    //do stuff
}

I know the code probably doesn't go anything like that, but how does it go?

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
JXPheonix
  • 2,618
  • 3
  • 16
  • 14
  • 1
    C# but similar in Java: http://stackoverflow.com/a/4077262/284240 ([Integer.MAX_VALUE](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#MAX_VALUE)) – Tim Schmelter Mar 27 '12 at 22:18
  • 1
    What would you gain out of this? `double` and `int` are represented in memory differently, and you would use one or the other based on the context of your memory handling. – Makoto Mar 27 '12 at 22:19
  • @Legend, i would have done the same as you suggested; do you by chance know how the %1 compares efficiency-wise to the Math.floor(variable) other users suggested? – G. Bach Mar 27 '12 at 22:26
  • 4
    @Makoto It's a program to find pygatorean triples. Square roots can sometimes be double, but at the same time they can also sometimes be intergers. You get what I mean? – JXPheonix Mar 27 '12 at 22:27
  • @JXPheonix: So values can either be a floating-point value or an integer value. Makes sense. – Makoto Mar 27 '12 at 22:29
  • Posted edited now with explanation. – Max Hudson Mar 27 '12 at 22:44
  • @G.Bach they are close to the same. –  Mar 27 '12 at 22:59
  • @JXPheonix: I think you meant "pythagorean" :) – G. Bach Mar 27 '12 at 23:27
  • @G. Bach haha, i believe i did. – JXPheonix Mar 27 '12 at 23:33
  • possible duplicate of [Fastest most efficient way to determine decimal value is integer in Java](http://stackoverflow.com/questions/1575052/fastest-most-efficient-way-to-determine-decimal-value-is-integer-in-java) – nawfal Jan 13 '13 at 00:12
  • possible duplicate of [Check if a number is a double or an int](http://stackoverflow.com/questions/7297975/check-if-a-number-is-a-double-or-an-int) – Old Pro May 14 '13 at 06:44

17 Answers17

284

Or you could use the modulo operator:

(d % 1) == 0

SkonJeet
  • 4,827
  • 4
  • 23
  • 32
165
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
    // integer type
}

This checks if the rounded-down value of the double is the same as the double.

Your variable could have an int or double value and Math.floor(variable) always has an int value, so if your variable is equal to Math.floor(variable) then it must have an int value.

This also doesn't work if the value of the variable is infinite or negative infinite hence adding 'as long as the variable isn't inifinite' to the condition.

Max Hudson
  • 9,961
  • 14
  • 57
  • 107
  • 3
    "If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument." http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#floor%28double%29 – Tim Schmelter Mar 27 '12 at 22:27
  • 2
    @TimSchmelter: good catch. It's also worth noting that NaN is not equal anything (including itself) but +/-Inf is equal to itself - so there are two edge cases! – maerics Mar 27 '12 at 22:33
  • Both Skon and Fouad posted much better answers. – Joel Christophel Nov 10 '13 at 06:04
  • @JoelChristophel: I don't agree. This is a good way as it eliminates the risk of type overflow. The only thing I didn't like was the assertion that the variable was an `int` if the `if` evaluates to `true`. – Bathsheba Dec 09 '15 at 13:02
  • @Bathsheba (Double.POSITIVE_INFINITY % 1) == 0 and its negative counterpart both evaluate to false. – Joel Christophel Dec 09 '15 at 16:24
  • Actually you're winning me round, in Java at least, where % for negatives is clearly defined. – Bathsheba Dec 09 '15 at 16:27
  • Modulo operator is very slow (see: http://stackoverflow.com/questions/27977834/why-is-modulus-operator-slow). So this answer is good, but Fouad answer is better because type casting is very fast. – Leonard Jun 09 '16 at 19:28
99

Guava: DoubleMath.isMathematicalInteger. (Disclosure: I wrote it.) Or, if you aren't already importing Guava, x == Math.rint(x) is the fastest way to do it; rint is measurably faster than floor or ceil.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
29
public static boolean isInt(double d)
{
    return d == (int) d;
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 1
    Only works for values in the `int` range. Using `long` has the same problem, but with a wider working range. – Bohemian Sep 04 '20 at 21:58
12

Try this way,

public static boolean isInteger(double number){
    return Math.ceil(number) == Math.floor(number); 
}

for example:

Math.ceil(12.9) = 13; Math.floor(12.9) = 12;

hence 12.9 is not integer, nevertheless

 Math.ceil(12.0) = 12; Math.floor(12.0) =12; 

hence 12.0 is integer

Sheldon
  • 519
  • 8
  • 20
6

Here is a good solution:

if (variable == (int)variable) {
    //logic
}
Nitish
  • 565
  • 4
  • 16
3

Consider:

Double.isFinite (value) && Double.compare (value, StrictMath.rint (value)) == 0

This sticks to core Java and avoids an equality comparison between floating point values (==) which is consdered bad. The isFinite() is necessary as rint() will pass-through infinity values.

simon.watts
  • 976
  • 10
  • 14
2

Here's a version for Integer and Double:

    private static boolean isInteger(Double variable) {
    if (    variable.equals(Math.floor(variable)) && 
            !Double.isInfinite(variable)          &&
            !Double.isNaN(variable)               &&
            variable <= Integer.MAX_VALUE         &&
            variable >= Integer.MIN_VALUE) {
        return true;
    } else {
        return false;
    }
}

To convert Double to Integer:

Integer intVariable = variable.intValue();
irudyak
  • 2,271
  • 25
  • 20
2

Similar to SkonJeet's answer above, but the performance is better (at least in java):

Double zero = 0d;    
zero.longValue() == zero.doubleValue()
2

My simple solution:

private boolean checkIfInt(double value){
 return value - Math.floor(value) == 0;
 }
Mostafa Amer
  • 192
  • 2
  • 13
1

Personally, I prefer the simple modulo operation solution in the accepted answer. Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:

if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
    // no decimal places
} else {
    // decimal places
}

Remainder(BigDecimal) returns a BigDecimal whose value is (this % divisor). If this one's equal to zero, we know there is no floating point.

1

Because of % operator cannot apply to BigDecimal and int (i.e. 1) directly, so I am using the following snippet to check if the BigDecimal is an integer:

value.stripTrailingZeros().scale() <= 0
Eric Tan
  • 1,377
  • 15
  • 14
1

A simple way for doing this could be

    double d = 7.88;    //sample example
    int x=floor(d);     //floor of number
    int y=ceil(d);      //ceil of number
    if(x==y)            //both floor and ceil will be same for integer number
        cout<<"integer number";
    else
        cout<<"double number";
1

My solution would be

double variable=the number;
if(variable-(int)variable=0.0){
 // do stuff
   }
dfmaaa1
  • 51
  • 7
1
public static boolean isInteger(double d) {
  // Note that Double.NaN is not equal to anything, even itself.
  return (d == Math.floor(d)) && !Double.isInfinite(d);
}
maerics
  • 151,642
  • 46
  • 269
  • 291
  • A more correct implementation would return false and you would have to write another method that takes int as argument and returns true. :D – alfa Mar 27 '12 at 22:23
0

you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:

public final double testRange = 0.2;

public static boolean doubleIsInteger(double d){
    int i = (int)d;
    double abs = Math.abs(d-i);
    return abs <= testRange;
}

If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.

Salvi94
  • 9
  • 2
-1

Here's a solution:

float var = Your_Value;
if ((var - Math.floor(var)) == 0.0f)
{
    // var is an integer, so do stuff
}
blalasaadri
  • 5,990
  • 5
  • 38
  • 58