Rounding round floor ceil trunc

suggest change

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

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

Python (and C++ and Java) round away from zero for negative numbers. Consider:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Math module:
* Rounding round floor ceil trunc

Table Of Contents
2 Filter
3 List
6 Math module
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve