In 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
, trunc
, and round
always return a float
.
round(1.3) # 1.0
round
always breaks ties away from zero.
round(0.5) # 1.0
round(1.5) # 2.0
floor
, ceil
, and trunc
always return an Integral
value, while round
returns an Integral
value if called with one argument.
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
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!
Python (and C++ and Java) round away from zero for negative numbers. Consider:
>>> math.floor(-1.7)
-2.0
>>> -5 // 2
-3