Home > Net >  Is there a prefab python function out there that turns only integer floats into ints?
Is there a prefab python function out there that turns only integer floats into ints?

Time:11-21

I would like to turn float integers (123.0) into ints (123).

What I would like the function to do:

Input: 2.1 Output: Exception, cannot turn float into int

Input: 2.0 Output: 2

Using int() on a float seems to just be math.floor() and that is not what I'm looking for.

CodePudding user response:

You can check if after you use int() it the same value as the float

def convert(num):
    if num == int(num):
        return int(num)
    raise Exception('Cannot turn float into int')

As a side note, using int() is not exactly as using math.floor(), try with negative numbers. What is the difference between int() and floor() in Python 3?

CodePudding user response:

I guess i would just do

def convert(n):
    return int(f"{n:g}")

CodePudding user response:

I don't know of a build 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 not be able to directly cast to int as it is in fact 0.9999999999999999! But this is a general issue with how floats are represented and not directly related to the used functions. So you'll encounter this with any method.

Here is an interesting post that goes a bit more into detail about the potential issues.

  • Related