Python舍入:圆,底,天花板,截头

示例

除了内置round功能,math模块提供floor,ceil以及trunc功能。

x = 1.55
y = -1.55

# 舍入到最接近的整数
round(x)       #  2
round(y)       # -2

# 第二个参数给出要舍入的小数位数(默认为0)
round(x, 1)    #  1个.6
round(y, 1)    # -1.6

# math是一个模块,因此请先将其导入,然后再使用它。
import math

# 获得小于x的最大整数
math.floor(x)  #  1
math.floor(y)  # -2

# 得到大于x的最小整数
math.ceil(x)   #  2
math.ceil(y)   # -1

# x的小数部分
math.trunc(x)  #  1, equivalent tomath.floorfor positive numbers
math.trunc(y)  # -1, equivalent tomath.ceilfor negative numbers

Python 2.x 2.7

floor,ceil,trunc,和round总是返回float。

round(1.3)  # 1个.0

round 总是从零断开联系。

round(0.5)  # 1个.0
round(1.5)  # 2.0
Python 3.x 3.0

floor,,ceil和trunc始终返回一个Integral值,而如果使用一个参数调用则round返回一个Integral值。

round(1.3)      # 1
round(1.33, 1)  # 1.3

round打破关系到最接近的偶数。当执行大量计算时,这可以纠正偏向较大数字的偏见。

round(0.5)  # 0
round(1.5)  # 2

警告!

与任何浮点表示一样,某些分数不能精确表示。这可能会导致一些意外的舍入行为。

round(2.675, 2)  # 2.67, not 2.68!

关于负数的下限,截断和整数除法的警告

对于负数,Python(以及C ++和Java)从零舍入。考虑:

>>> math.floor(-1.7)
-2.0
>>> -5 // 2
-3