如果数学上是 int,如何将 float 更改为 int?2.0 -> 2. 2.5 -> 2.5

0 python

例如

def asdf(x): 
    return (x / 2) 


asdf(4.0)
asdf(5.0)
Run Code Online (Sandbox Code Playgroud)

的返回值 2.0将被转换为22.5不会被转换为2.

Mec*_*Pig 5

float对象有一个float.is_integer判断是否为整数的方法:

>>> 2.0.is_integer()
True
>>> 2.1.is_integer()
False
Run Code Online (Sandbox Code Playgroud)

因此,如果它返回 true,您可以将其转换为整数:

>>> def asdf(x):
...     res = x / 2
...     return int(res) if res.is_integer() else res
...
>>> asdf(4.0)
2
>>> asdf(5.0)
2.5
Run Code Online (Sandbox Code Playgroud)