Skip to main content
 首页 » 编程设计

Python之将 float 四舍五入为整数的最佳方法是什么

2025年05月04日18lori

我有一个 float ,我想将其四舍五入为整数,但总是四舍五入(其中“向上”表示幅度较大)

例如,4.2 将四舍五入为 5,-4.2 将四舍五入为 -5.0

有没有内置于 Python 中的好方法来执行此操作?如果不是,您会推荐什么作为执行此操作的最有效方法?

最初我只是使用 math.ceil(),直到我意识到 math.ceil(4.2) 给出 5,而 math.ceil(-4.2 ) 给出-4,这不是我想要的。

解决这个问题的一种方法是对正数使用 ceil,对负数使用 floor,但是如果内联,代码开始看起来真的很恶心语句无处不在(我在多个地方使用这个操作)

另一种可能性可能是 math.copysign( math.ceil( abs( x ) ), x ) ,这似乎也有点过分了

请您参考如下方法:

but the code starts to look really gross with inline if statements everywhere (I use this operation in multiple places)

然后写一个函数:

def myround(flt): 
   return math.ceil(flt) if flt > 0.0 else math.floor(flt)