0

I need to check if a value is an integer in Python. Note that by integer I mean values like 2, 1.0 and -4.0000, whereas 0.4 and -2.3 are not integers.

How can I do this?

becko
  • 15,722
  • 27
  • 80
  • 155
  • 1
    Also, `float(obj) == int(float(obj))` – inspectorG4dget Oct 31 '14 at 19:01
  • When someone votes to close, there's a comment as to why. In this case, there appears to be another post which already answers your question. Check it out – inspectorG4dget Oct 31 '14 at 19:03
  • @inspectorG4dget Oh... I missed that because the most accepted and upvoted answer there only tells you if `value` is of *type* `int`, which is not what I want (I accept `1.0` as an integer). – becko Oct 31 '14 at 19:14

1 Answers1

1

float instances have an is_integer method, which tells you whether f == int(f). The following snippet will therefore work for both integers and floats, as well as any strings representing either of those numerical types:

float(value).is_integer()
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376