I don't know of a built-in that does it directly, but it is easy to create your own function. You can use .is_integer()
on the input-value to check if the float is directly castable to int:
def strict_int(value):
if value.is_integer():
return int(value)
raise ValueError("cannot turn uneven float into int")
print(strict_int(3.0))
print(strict_int(3.1))
Output:
3
...
ValueError: cannot turn uneven float into int
But be warned, that there may be some unexpected behavior resulting from the way floats are represented. Try this for example:
print(strict_int(0.3 + 0.3 + 0.3 + 0.1))
This "1.0" will fail when trying to strictly convert to an int as it is in fact 0.9999999999999999! If you use the standard int it will work in that it gives you a result, but the result for int(0.3 + 0.3 + 0.3 + 0.1)
is 0, probably not what you'd expect. But this is a general issue with how floats are represented and not directly related to the used methods. So you'll encounter this anywhere floats are present.
Here is an interesting post that goes a bit more into detail about the potential issues.