How to check if a float value is a whole number How to check if a float value is a whole number python python

# How to check if a float value is a whole number

To check if a float value is a whole number, use the `float.is_integer()` method:

``>>> (1.0).is_integer()True>>> (1.555).is_integer()False``

The method was added to the `float` type in Python 2.6.

Take into account that in Python 2, `1/3` is `0` (floor division for integer operands!), and that floating point arithmetic can be imprecise (a `float` is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:

``>>> for n in range(12000, -1, -1):...     if (n ** (1.0/3)).is_integer():...         print n... 27810``

which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:

``>>> (4**3) ** (1.0/3)3.9999999999999996>>> 10648 ** (1.0/3)21.999999999999996``

You'd have to check for numbers close to the whole number instead, or not use `float()` to find your number. Like rounding down the cube root of `12000`:

``>>> int(12000 ** (1.0/3))22>>> 22 ** 310648``

If you are using Python 3.5 or newer, you can use the `math.isclose()` function to see if a floating point value is within a configurable margin:

``>>> from math import isclose>>> isclose((4**3) ** (1.0/3), 4)True>>> isclose(10648 ** (1.0/3), 22)True``

For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:

``def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``

We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as `x % y`. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.

This function will return a boolean, `True` or `False`, depending on whether `n` is a whole number.

``def is_whole(n):    return n % 1 == 0``

You could use this:

``if k == int(k):    print(str(k) + " is a whole number!")``