如何在Python中四舍五入一个数字向上?

我试过四舍五入,但它把数字四舍五入了。例子:

round(2.3) = 2.0 

而不是我想要的3。

我尝试了int(number + .5),但它再次四舍五入!例子:

int(2.3 + .5) = 2

当前回答

四舍五入的值应该是浮动的

a = 8 
b = 21
print math.ceil(a / b)
>>> 0

but

print math.ceil(float(a) / b)
>>> 1.0

其他回答

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

该函数不需要模块。

使用数学。Ceil整理:

>>> import math
>>> math.ceil(5.4)
6.0

注意:输入应该是浮点数。

如果你需要一个整数,调用int来转换它:

>>> int(math.ceil(5.4))
6

顺便说一下,用数学。向下舍入和舍入到最接近的整数。

>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)

你可能也喜欢numpy:

>>> import numpy as np
>>> np.ceil(2.3)
3.0

我并不是说numpy比数学更好,但如果您已经将numpy用于其他目的,则可以保持代码的一致性。

总之,这是我偶然发现的一个细节。我经常使用numpy,很惊讶没有人提到它,但当然,公认的答案是完全正确的。

你可以这样使用round:

cost_per_person = round(150 / 2, 2)

  

对于那些想四舍五入a / b并得到整数的人:

使用整数除法的另一种变体是

def int_ceil(a, b):
    return (a - 1) // b + 1

>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5

注:a、b必须为非负整数