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

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

round(2.3) = 2.0 

而不是我想要的3。

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

int(2.3 + .5) = 2

当前回答

如果处理整数,一种四舍五入的方法是利用//四舍五入的事实:只对负数进行除法,然后对结果求负数。不需要导入、浮点数或条件。

rounded_up = -(-numerator // denominator)

例如:

>>> print(-(-101 // 5))
21

其他回答

您可以使用楼层划分并添加1。 2.3 // 2 + 1

你可以这样使用round:

cost_per_person = round(150 / 2, 2)

  

X * -1 // 1 * -1

令人困惑,但它是有效的:当x=7.1时,你得到8.0。当x = -1.1时,得到-1.0

不需要导入模块。

你可能也喜欢numpy:

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

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

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

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

该函数不需要模块。