9
$\begingroup$

I can't figure out how to test if a number is an integer.

I have found IntegerQ, but this function only checks if the type of the input is an integer, not whether the number it represents actually is one (IntegerQ[3.0] returns False).

Element[3.0, Integers] also does not return True.

I'm probably missing something obvious. There must be an easy way to do this.

$\endgroup$
  • $\begingroup$ check if FractionalPart is zero, or smaller than some epsilon $\endgroup$ – george2079 Jun 4 '17 at 12:13
  • $\begingroup$ Closely related: (7463) $\endgroup$ – Mr.Wizard Jun 4 '17 at 12:42
9
$\begingroup$

you can try this:

integerQ[x_] := x == Round[x]
$\endgroup$
  • 3
    $\begingroup$ One has to be aware of the approximations that the Equal function makes, though. 1.000000000000001 == Round[1.000000000000001] is true, but 0.000000000000001 == Round[0.000000000000001] is false. $\endgroup$ – mistercake Jun 4 '17 at 14:50
4
$\begingroup$
on suggestion of @george2079
checkInteger[num_] := (# === 0. || # === 0) &@FractionalPart[num]
$\endgroup$
  • $\begingroup$ Can you explain why you didn't just use # == 0 instead of (# === 0. || # === 0)? $\endgroup$ – mistercake Jun 4 '17 at 12:38
  • 1
    $\begingroup$ @mistercake for your problem it does not matter. you can choose to use == (Equal) instead of === (SameQ). SameQ is usually used to check if two expressions are identical in form. for example 3.0 == 3 will yield True whereas 3.0===3 will yield False $\endgroup$ – Ali Hashmi Jun 4 '17 at 12:46
  • 1
    $\begingroup$ @mistercake also checkInteger[num_] := FractionalPart[num] === 0 will not work properly if you use checkInteger[3.0] because 0. === 0 returns False. You can use checkInteger[num_] := FractionalPart[num] == 0 instead $\endgroup$ – Ali Hashmi Jun 4 '17 at 12:49
3
$\begingroup$

Define

intQ = IntegerQ@Rationalize@# &;

Then

intQ@3.0

True

and

intQ@2.2

False

$\endgroup$
  • 1
    $\begingroup$ I like using the equivalent Composition version: intQ = IntegerQ @* Rationalize $\endgroup$ – Carl Woll Jun 4 '17 at 16:29
0
$\begingroup$

You can also check if your number mod 1 is zero

$\endgroup$
  • 1
    $\begingroup$ This method has a significant bias in its false positives though. Using f[x_] := (Mod[x, 1] == 0), f[100000000000.000000001] is True while f[99999999999.999999999]. While this isn't likely to be an actual issue in most applications, it is worth remembering that values only slightly above an integer may be reported as integers using this method, while values that are slightly below will almost certainly not be. Every other answer here reports at least one false positive on those 2 numbers though. $\endgroup$ – eyorble Jul 10 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.