在Python中,我发现了两种获取楼层的方法:
3.1415 // 1
和/或
import mathmath.floor(3.1415)
import math
math.floor(3.1415)
第一种方法的问题是它返回一个浮点数(即3.0)。第二种方法让人感觉笨拙而且太长。在Python中是否有替代的解决方案?
3.0
ao218c7q1#
只要你的数字是正数,你可以简单地转换成int来向下舍入到下一个整数:
int
>>> int(3.1415)3
>>> int(3.1415)
3
对于负整数,这将向上舍入。
wh6knrhe2#
你可以在float上调用int()来强制转换到较低的int(不明显是地板,但更优雅)
int(3.745) #3
或者调用int对地板结果。
from math import floorf1 = 3.1415f2 = 3.7415print floor(f1) # 3.0print int(floor(f1)) # 3print int(f1) # 3print int(f2) # 3 (some people may expect 4 here)print int(floor(f2)) # 3
from math import floor
f1 = 3.1415
f2 = 3.7415
print floor(f1) # 3.0
print int(floor(f1)) # 3
print int(f1) # 3
print int(f2) # 3 (some people may expect 4 here)
print int(floor(f2)) # 3
http://docs.python.org/library/functions.html#int
xoefb8l83#
第二种方法是可行的,但有一种方法可以缩短它。
from math import floorfloor(3.1415)
floor(3.1415)
yrefmtwq4#
请注意,发言权和转换为整数并不是一回事,负数。如果您真的希望地板是一个整数,那么应该在调用math.floor()之后转换为一个int。
>>> int(-0.5)0>>> math.floor(-0.5)-1.0>>> int(math.floor(-0.5))-1
>>> int(-0.5)
0
>>> math.floor(-0.5)
-1.0
>>> int(math.floor(-0.5))
-1
ztyzrc3y5#
如果不想要float,请将其转换为int
float
int(3.1415 // 1)
p4tfgftt6#
from math import floordef ff(num, step=0): if not step: return floor(num) if step < 0: mplr = 10 ** (step * -1) return floor(num / mplr) * mplr ncnt = step if 1 > step > 0: ndec, ncnt = .0101, 1 while ndec > step: ndec *= .1 ncnt += 1 mplr = 10 ** ncnt return round(floor(num * mplr) / mplr, ncnt)
def ff(num, step=0):
if not step:
return floor(num)
if step < 0:
mplr = 10 ** (step * -1)
return floor(num / mplr) * mplr
ncnt = step
if 1 > step > 0:
ndec, ncnt = .0101, 1
while ndec > step:
ndec *= .1
ncnt += 1
mplr = 10 ** ncnt
return round(floor(num * mplr) / mplr, ncnt)
您可以使用正数/负数和浮点.1,.01,.001...
hec6srdp7#
number = 1.23456leftnumber = int(str(number).split('.')[0])rightnumber = str(number ).split('.')[1]
number = 1.23456
leftnumber = int(str(number).split('.')[0])
rightnumber = str(number ).split('.')[1]
7条答案
按热度按时间ao218c7q1#
只要你的数字是正数,你可以简单地转换成
int
来向下舍入到下一个整数:对于负整数,这将向上舍入。
wh6knrhe2#
你可以在float上调用int()来强制转换到较低的int(不明显是地板,但更优雅)
或者调用int对地板结果。
http://docs.python.org/library/functions.html#int
xoefb8l83#
第二种方法是可行的,但有一种方法可以缩短它。
yrefmtwq4#
请注意,发言权和转换为整数并不是一回事,负数。如果您真的希望地板是一个整数,那么应该在调用math.floor()之后转换为一个int。
ztyzrc3y5#
如果不想要
float
,请将其转换为int
p4tfgftt6#
您可以使用正数/负数和浮点.1,.01,.001...
hec6srdp7#