[英]Python - What is the best way to round a float up in magnitude to an integer
I have a floating point number which I would like to round to an integer, but always round up (where 'up' means larger in magnitude) 我有一个浮点数,我想四舍五入为整数,但总是四舍五入(其中“ up”表示幅度较大)
For example, 4.2 would be rounded to 5, and -4.2 would be rounded to -5.0 例如,将4.2舍入为5,将-4.2舍入为-5.0
Is there a nice way to do this that is built into Python? 有内置在Python中的好方法吗? If not, what would you recommend as the most efficient way of performing this operation? 如果没有,您将推荐什么作为执行此操作的最有效方法?
Originally I was just using math.ceil()
, until I realized math.ceil(4.2)
gives 5, while math.ceil(-4.2)
gives -4, which is not what I want. 最初我只是使用math.ceil()
,直到我意识到math.ceil(4.2)
给出5,而math.ceil(-4.2)
给出-4,这不是我想要的。
One way that to get around this is to use ceil
for positive numbers, and floor
for the negative ones, but the code starts to look really gross with inline if statements everywhere (I use this operation in multiple places) 解决此问题的一种方法是使用ceil
表示正数,使用floor
表示负数,但是代码随处可见,内联if语句看起来真的很粗糙(我在多个地方使用了此操作)
Another possibility might be something like math.copysign( math.ceil( abs( x ) ), x )
which also seems a little excessive 另一种可能性可能是诸如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) 但是代码随处可见,内联if语句看起来真的很粗糙(我在多个地方使用了此操作)
Then write a function: 然后编写一个函数:
def myround(flt):
return math.ceil(flt) if flt > 0.0 else math.floor(flt)
If you don't want to scatter "inline if statements everywhere", you could defined your own function: 如果您不想散布“内联if语句无处不在”,则可以定义自己的函数:
def my_rounding(x):
return math.ceil(x) if x > 0. else math.floor(x)
:D :D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.