0

In Python, if I have a list with float numbers, how can I find all entries, which are round figures?

e.g. Checking x=[1.234,0.000000,2.0,0.0001] gives output

  >>>     False
          True
          True
          False

I tried isinstance function, which did not worked :

x=[1.234,0.000000,2.0,0.0001]
for i in x:
    print(isinstance(i, int))

I guess technically 2.0 and such are not of type integers. So I can not use it like that.

SOAP
  • 159
  • 1
  • 1
  • 5

1 Answers1

2

Using isinstance does not work, as those are technically still all float:

>>> x = [1.234, 0.000000, 2.0, 0.0001]
>>> [type(n) for n in x]
[float, float, float, float]

But you can check whether the value, converted to an int, is equal to the original value:

>>> [n == int(n) for n in x]
[False, True, True, False]

Or, as pointed out in comments, using float.is_integer:

>>> [n.is_integer() for n in x]
[False, True, True, False]
tobias_k
  • 81,265
  • 12
  • 120
  • 179