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

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

round(2.3) = 2.0 

而不是我想要的3。

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

int(2.3 + .5) = 2

当前回答

如果有人想四舍五入到一个特定的小数点后:

import math
def round_up(n, decimals=0):
    multiplier = 10 ** decimals
    return math.ceil(n * multiplier) / multiplier

其他回答

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

该函数不需要模块。

试试这个:

a = 211.0
print(int(a) + ((int(a) - a) != 0))

使用数学。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)

这里有一种使用模和bool的方法

n = 2.3
int(n) + bool(n%1)

输出:

3

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

round(integer) + 1