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

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

round(2.3) = 2.0 

而不是我想要的3。

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

int(2.3 + .5) = 2

当前回答

的数学。函数返回大于或等于x的最小整数。

对于Python 3:

import math
print(math.ceil(4.2))

对于Python 2:

import math
print(int(math.ceil(4.2)))

其他回答

我基本上是Python的初学者,但如果你只是想四舍五入而不是向下,为什么不这样做:

round(integer) + 1

毫无意义地做:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3

我很惊讶居然没有人建议

(numerator + denominator - 1) // denominator

整数除法的四舍五入。曾经是C/ c++ /CUDA (cf. divup)的常用方式

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

rounded_up = -(-numerator // denominator)

例如:

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

我的分享

我已经测试了print(-(-101 // 5)) = 21上面给出的例子。

现在来总结一下:

101 * 19% = 19.19

我不能用**,所以我把乘除展开:

(-(-101 //(1/0.19))) = 20