取浮点数的整数部分

50

我发现在Python中有两种取整方式:

3.1415 // 1

并且

import math
math.floor(3.1415)

第一种方法的问题在于它返回一个浮点数(即3.0)。第二种方法感觉笨拙且太长。

在Python中,是否有其他的取整解决方案?


8
选第二个。它没有问题。 - Karoly Horvath
5
你可以始终调用int(3.1415),但它会向0四舍五入而不是向下取整,对于小于0的数字会产生不同的结果。 - Thomas Orozco
http://uncyclopedia.wikia.com/wiki/Pi_equals_exactly_three - wim
或者你可以使用 int(3.1415 // 1),它的作用类似于 math.floor。 - Stam Kaly
7个回答

75
只要你的数字是正数,你可以简单地将其转换为 int 来向下取整到下一个整数:
>>> int(3.1415)
3

对于负整数,这会向上舍入。


要将任何数字(正数和负数)向下舍入,仍然可以使用 int(n // 1),例如 int(-3.14 // 1) 将得到 -4。当然,只有在可能出现负数时才有用。 - zezollo
除非你想让代码读者困惑,否则使用int(math.floor(x))比使用整除1更好,因为它的作用立即显而易见。 - Sven Marnach

14

您可以在浮点数上调用int()函数以将其强制转换为较低的整数(不是明显的floor但更优雅)

int(3.745)  #3

或者对 floor 结果调用 int。

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


1
为什么人们会期望 int(f2) 的结果是 4 - Randomblue
1
因为您可能期望它四舍五入到最接近的整数而不是较小的整数。 - Matt Alcock
3
OP使用的是Python 3.x,这在帖子中不太明显。在Python 3.x中,math.floor()返回一个int,因此不需要转换返回值。 - Sven Marnach

6
第二种方法是正确的选择,但有一个缩短方法。
from math import floor
floor(3.1415)

2
在Python3中,floor()函数返回一个整数,但在Python2中它返回一个浮点数。 - Eugene Yarmash
@eugeney,我只是想指出有一种方法可以省略math.部分。我不知道为什么他们一开始没有抱怨从floor返回float结果?感谢您告诉我从2到3的更改,我不知道这个。这很有道理,直到从2.4开始,任意大小的整数可以与普通整数互换,floor才能返回一个int - Mark Ransom

5

请注意,对于负数来说,取整和强制转换为整数并不是同一件事。如果您真的想要作为整数的取整结果,则应在调用math.floor()函数后将其强制转换为整数。

>>> int(-0.5)
0
>>> math.floor(-0.5)
-1.0
>>> int(math.floor(-0.5))
-1

4

如果您不想要一个 float,请将其转换为 int

int(3.1415 // 1)

0
from math import floor


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...


0
number = 1.23456
leftnumber = int(str(number).split('.')[0])
rightnumber = str(number ).split('.')[1]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接