如何在Python中四舍五入一个数字向上?
我试过四舍五入,但它把数字四舍五入了。例子:
round(2.3) = 2.0
而不是我想要的3。
我尝试了int(number + .5),但它再次四舍五入!例子:
int(2.3 + .5) = 2
如何在Python中四舍五入一个数字向上?
我试过四舍五入,但它把数字四舍五入了。例子:
round(2.3) = 2.0
而不是我想要的3。
我尝试了int(number + .5),但它再次四舍五入!例子:
int(2.3 + .5) = 2
当前回答
你可以这样使用round:
cost_per_person = round(150 / 2, 2)
其他回答
的数学。函数返回大于或等于x的最小整数。
对于Python 3:
import math
print(math.ceil(4.2))
对于Python 2:
import math
print(int(math.ceil(4.2)))
使用数学。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)
试试这个:
a = 211.0
print(int(a) + ((int(a) - a) != 0))
我知道这个答案是以前的一个问题,但如果你不想输入数学,你只想四舍五入,这对我来说很有用。
>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5
第一部分变成4,如果有余数,第二部分计算为“True”,加上True = 1;False = 0。如果没有余数,它还是原来的整数,但如果有余数,它就加1。
我的分享
我已经测试了print(-(-101 // 5)) = 21上面给出的例子。
现在来总结一下:
101 * 19% = 19.19
我不能用**,所以我把乘除展开:
(-(-101 //(1/0.19))) = 20