Rounding round floor ceil trunc
suggest changeIn addition to the built-in round function, the math module provides the floor, ceil, and trunc functions.
x = 1.55
y = -1.55
# round to the nearest integer
round(x) # 2
round(y) # -2
# the second argument gives how many decimal places to round to (defaults to 0)
round(x, 1) # 1.6
round(y, 1) # -1.6
# math is a module so import it first, then use it.
import math
# get the largest integer less than x
math.floor(x) # 1
math.floor(y) # -2
# get the smallest integer greater than x
math.ceil(x) # 2
math.ceil(y) # -1
# drop fractional part of x
math.trunc(x) # 1, equivalent to math.floor for positive numbers
math.trunc(y) # -1, equivalent to math.ceil for negative numbers
floor, ceil, and trunc return an int. round returns an int when called with one argument, and a float when a second argument gives the number of decimal places. In Python 2, all four returned a float, and round broke ties away from zero.
round(1.3) # 1
round(1.33, 1) # 1.3
round breaks ties towards the nearest even number. This corrects the bias towards larger numbers when performing a large number of calculations.
round(0.5) # 0
round(1.5) # 2
Warning!
As with any floating-point representation, some fractions cannot be represented exactly. This can lead to some unexpected rounding behavior.
round(2.675, 2) # 2.67, not 2.68!
Warning about the floor, trunc, and integer division of negative numbers
math.floor and // round toward negative infinity, so a negative result moves away from zero. math.trunc rounds toward zero.
>>> math.floor(-1.7)
-2
>>> math.trunc(-1.7)
-1
>>> -5 // 2
-3