Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python round() function

Reference for Python round(): round to a number of digits, why round(2.5) is 2, negative ndigits, float surprises and using decimal for exact rounding.

The built-in round() function rounds a number to a given number of decimal digits. With one argument it rounds to the nearest integer and returns an int; with ndigits it keeps the type of the input (a float stays a float).

Python rounds halves to the nearest even number, often called banker's rounding: round(0.5) is 0, round(1.5) is 2 and round(2.5) is 2. This reduces systematic bias when many values are rounded, but it surprises people who expect "round half up".

Python
round(3.7)        # 4
round(3.14159, 2) # 3.14
round(1234, -2)   # 1200

Try it

Python Rounding basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Float surprises and exact alternatives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
round(number)
round(number, ndigits)
Name Description
number An int, float, Fraction, Decimal or any object defining __round__().
ndigits Optional number of digits after the decimal point. Negative values round to tens, hundreds, ... None behaves like omitting it.

Return value: an int if ndigits is omitted or None; otherwise a number of the same type as number.

Raises: TypeError for non-numbers; OverflowError for infinity; ValueError for NaN when converting to an int.

Usage notes

  • Halves go to the even neighbor. round(0.5) is 0, round(2.5) is 2, round(3.5) is 4. If you need school-style rounding, use decimal with ROUND_HALF_UP.
  • Floats are approximations. 2.675 is stored as slightly less than 2.675, so round(2.675, 2) gives 2.67. This is not a bug in round; the stored number really is below the half.
  • Money: do not round binary floats. Use decimal.Decimal with quantize(), or store integer cents.
  • round(x) returns an int, round(x, 0) returns a float such as 3.0. That is a classic source of surprises in output.
  • Negative ndigits rounds to the left of the decimal point: round(1234, -2) is 1200.
  • round() rounds the value; formatting only changes the display. f"{x:.2f}" produces a string and leaves x alone. Format specs also use round-half-even on the exact stored value.
  • Other directions: math.floor (down), math.ceil (up), math.trunc (toward zero) and int() (truncation).
  • Custom types can support round() by implementing __round__(self, ndigits=None).