Coding

How to Round in Python: round(), Decimal, floor and ceil

To round in Python, call round(number, ndigits): round(3.14159, 2) returns 3.14, and round(7.6) returns the integer 8. Be aware that Python rounds exact ties to the nearest even result, so round(2.5) is 2, and that floats can surprise you: round(2.675, 2) gives 2.67.

The basics of round()

The built-in round() takes a number and an optional number of digits after the decimal point:

round(3.14159, 2)   # 3.14
round(3.14159, 3)   # 3.142
round(7.6)          # 8
round(7.4)          # 7

The documentation defines it this way: with ndigits omitted or None, it returns the nearest integer to its input. Otherwise values are rounded to the closest multiple of 10 to the power minus ndigits.

The return type depends on that second argument. Without ndigits (or with None) you get an int. With ndigits, the result has the same type as the input, so a float stays a float:

type(round(7.6))      # <class 'int'>
type(round(7.6, 0))   # <class 'float'>
round(7.6, 0)         # 8.0

How to round to tens, hundreds and thousands

Any integer is a valid ndigits, including negative ones. A negative value rounds to the left of the decimal point:

round(1234, -1)     # 1230
round(1234, -2)     # 1200
round(1234, -3)     # 1000
round(1264.7, -2)   # 1300.0

Because the input in the last line is a float, the result is a float. Pass an integer if you want an integer back.

Why round(2.5) returns 2: ties go to the even number

Many people expect "round half up", where 0.5 always goes up. Python 3 does not do that. The documentation says that if two multiples are equally close, rounding is done toward the even choice, and gives these examples: both round(0.5) and round(-0.5) are 0, and round(1.5) is 2.

Applying the same rule gives these results:

CallResultWhy
round(0.5)0Tie between 0 and 1, 0 is even
round(1.5)2Tie between 1 and 2, 2 is even
round(2.5)2Tie between 2 and 3, 2 is even
round(3.5)4Tie between 3 and 4, 4 is even
round(-2.5)-2Tie between -3 and -2, -2 is even
round(1250, -2)1200Tie between 1200 and 1300, 1200 has the even hundreds digit

This is often called banker's rounding. Its advantage is that ties go up about as often as they go down, so rounding a long list of numbers does not drift in one direction. If your task needs ties to go up, use the decimal approach below.

Why round(2.675, 2) gives 2.67

The Python documentation calls this out with a note: round(2.675, 2) gives 2.67 instead of the expected 2.68. It says this is not a bug, but a result of the fact that most decimal fractions cannot be represented exactly as a float.

A float is a binary fraction. The tutorial on floating-point arithmetic shows the same effect with 0.1: the closest double is a tiny bit larger than 1/10, and it can never be exactly 1/10. The number 2.675 has the same problem. The stored value is a hair below 2.675, so it is not a tie at all, and it rounds down. You can see the exact stored value with the decimal module:

from decimal import Decimal

Decimal(2.675)

Example output (the digits after the first few are shown by the exact conversion):

Decimal('2.67499999999999982236431605997495353221893310546875')

The practical rule: when a float looks like it ends in a 5 at the rounding position, do not assume it is a tie. It may be slightly above or slightly below.

How to round half up with the decimal module

When you need exact decimal rounding, such as prices, build a Decimal from a string and call quantize(). The documentation describes quantize() as returning a value equal to the first operand after rounding and having the exponent of the second operand:

from decimal import Decimal, ROUND_HALF_UP

price = Decimal("2.675")
price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)   # Decimal('2.68')

Here "2.675" is stored exactly, so it is a true tie, and ROUND_HALF_UP sends it away from zero. Always pass a string. Decimal(2.675) starts from the already-inexact float and would carry the error with it.

If you omit rounding, quantize() uses the rounding mode of the current context. The default context uses ROUND_HALF_EVEN, which is the same tie rule as round(). The documented modes are:

ModeDocumented behavior
ROUND_HALF_EVENRound to nearest with ties going to the nearest even integer
ROUND_HALF_UPRound to nearest with ties going away from zero
ROUND_HALF_DOWNRound to nearest with ties going towards zero
ROUND_DOWNRound towards zero
ROUND_CEILINGRound towards Infinity
ROUND_FLOORRound towards -Infinity

The decimal page also gives this example of a different mode: Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) returns Decimal('7.32').

How to round up or down: ceil, floor and trunc

round() picks the nearest value. To always go in one direction, use the math module:

import math

math.ceil(2.1)    # 3   smallest integer greater than or equal to x
math.floor(2.9)   # 2   largest integer less than or equal to x
math.trunc(2.9)   # 2   fractional part removed

The three differ only for negative numbers. floor() goes toward negative infinity, ceil() toward positive infinity, and trunc() toward zero. The documentation says trunc() is equivalent to floor() for positive input and to ceil() for negative input:

Inputfloorceiltruncround
2.52322
-2.5-3-2-2-2
2.72323
-2.7-3-2-2-3

These functions round to whole numbers only. To round up to two decimals, scale first, or use Decimal with ROUND_CEILING or ROUND_FLOOR in quantize().

How to round only for display

If you only want a number to look rounded in output, you do not need to change the value. Use a format specification:

value = 1234567.891

f"{value:.2f}"     # '1234567.89'
f"{value:,.2f}"    # '1,234,567.89'
f"{value:.0f}"     # '1234568'

In the format mini-language, .2f means fixed-point with two digits after the decimal point, and , adds a thousands separator. Without a precision, the f type uses 6 digits after the decimal point. The documentation says the rounding mode for floats matches that of round(), and for Decimal the current context's rounding mode is used, so f"{2.675:.2f}" gives '2.67' for the same reason round(2.675, 2) does.

Formatting returns a string. If you need to keep calculating, keep the unrounded number and format at the last step. Rounding at every step of a calculation compounds the error.

Which method to use

  • Plain numeric work, ties rarely matter: round(x, n).
  • Always up or always down to an integer: math.ceil() or math.floor().
  • Cut off the decimals: math.trunc().
  • Money, or ties must go up: Decimal built from strings, with quantize() and an explicit rounding mode.
  • Only showing a number: an f-string such as f"{x:.2f}".

If the result is not what you expected

Check three things. First, the type: if you passed a float with ndigits, you get a float, so round(7.6, 0) prints 8.0. Second, whether the input is really a tie: print Decimal(your_float) to see the exact stored value. Third, whether the rounding mode of your Decimal context is the one you think it is. The default is ROUND_HALF_EVEN, so a bare quantize() does not round half up.

Frequently asked questions

Why does round(2.5) return 2 in Python?
Python 3 rounds ties to the nearest even result, not away from zero. 2.5 is exactly halfway between 2 and 3, so round(2.5) returns 2, while round(3.5) returns 4. The documentation gives round(0.5) and round(-0.5) as 0 and round(1.5) as 2.
Why does round(2.675, 2) give 2.67 instead of 2.68?
The float 2.675 is stored in binary and is not exactly 2.675. Its stored value sits slightly below the midpoint, so it rounds down. The Python documentation says this is not a bug but a result of most decimal fractions not being exactly representable as floats. Use decimal.Decimal('2.675') if you need exact decimal behaviour.
How do I round to the nearest integer and get an int?
Call round() with one argument, for example round(7.6), which returns 8 as an int. With ndigits omitted or None, round() returns an integer. If you pass ndigits, even 0, a float input gives a float back.
Should I round money values with round() or Decimal?
Use decimal.Decimal for money. Decimal values store decimal digits exactly, and quantize() lets you choose the rounding mode, such as ROUND_HALF_UP. Rounding binary floats can land on the wrong side of a half-cent.

Sources