如何在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
当前回答
使用数学。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)
其他回答
X * -1 // 1 * -1
令人困惑,但它是有效的:当x=7.1时,你得到8.0。当x = -1.1时,得到-1.0
不需要导入模块。
没有导入math //使用基本环境:
A)方法/类方法
def ceil(fl):
return int(fl) + (1 if fl-int(fl) else 0)
def ceil(self, fl):
return int(fl) + (1 if fl-int(fl) else 0)
b)λ:
ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)
四舍五入的值应该是浮动的
a = 8
b = 21
print math.ceil(a / b)
>>> 0
but
print math.ceil(float(a) / b)
>>> 1.0
当你在python中操作4500/1000时,结果将是4,因为默认的python将结果假设为整数,逻辑上: 4500/1000 = 4.5——> int(4.5) = 4 4的上限值显然是4
使用4500/1000.0,结果将是4.5,cil为4.5—> 5
使用javascript你会收到4.5作为4500/1000的结果,因为javascript只假设结果为“数字类型”,并直接返回结果为浮点数
祝你好运! !
你可以这样使用round:
cost_per_person = round(150 / 2, 2)