如何将浮点数四舍五入到最接近的最大整数



例如,我有 1.242533222,我想将其四舍五入为 2。换句话说,我想将浮点数四舍五入到最接近的最大整数。如何在Python 3中做到这一点?

我想将浮点数四舍五入到最接近的最大整数。例如 1.232323 到 2,5.12521369 到 6,7.12532656 到 8

你正在寻找一个数字的上限,Python 通过 math.ceil() 函数提供:

$ python3
Python 3.2.5 (default, Jul 30 2013, 20:11:30)
[GCC 4.8.1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.ceil(1.232323)
2
>>> math.ceil(5.12521369)
6
>>> math.ceil(7.12532656)
8

许多语言都有数学库。显然在 Python 中,它看起来像这样:

math.ceil(1.24533222).

见 http://docs.python.org/2/library/math.html

如果要在 int 数据类型中执行此操作,请执行以下操作:

int(math.ceil(1.24533222))
如果你想

浮点,试试使用float!

float(math.ceil(5.12521369))

否则

math.ceil(5.12521369)

如果您不想导入数学:

def ceil(num):
    floor = int(num)
    if floor != num:
        return floor + 1
    return floor

最新更新