Python round() Function

Returns a number rounded to specified precision

Usage

The round() returns a number rounded to ndigits precision after the decimal point.

If ndigits is not specified, the number is rounded to the nearest integer.

Syntax

round(number,ndigits)

Python round() function parameters
ParameterConditionDescription
numberRequiredSpecifies the number to round
ndigitsOptionalSpecifies the number of decimal digits to round to.
Default is None.

Basic Example

Example: Round a number 2.8 to the nearest integer

x = round(2.8)
print(x)	# 3

Rounding to decimal places

You can specify precision after the decimal point by using ndigits parameter.

Example: Round a number to only two decimals

x = round(2.86542, 2)
print(x)	# 2.87

Round To Ten’s or Hundred’s

ndigits can be negative as well. It allows you to e.g. round numbers to ten’s or hundred’s.

Example:

# Round to ten's
x = round(48, -1)
print(x)  # 50

x = round(148, -1)
print(x)  # 150
# Round to hundred's
x = round(248, -2)
print(x)  # 200

x = round(268, -2)
print(x)  # 300

Rounding Conversion

If ndigits is not specified, the return value is an integer. Otherwise the return value has the same type as number.

Example:

# returns int
x = round(2.865)
print(x)	# 3
# returns float
x = round(2.865, 0)
print(x)	# 3.0

Rounding to Even (Banker’s Rounding)

In Python, if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then the even number is returned.

This kind of rounding is called rounding to even (or banker’s rounding).

Example: Rounding to even

x = round(4.5)
print(x)  # 4
x = round(5.5)
print(x)  # 6

Rounding Up/Down

If you want to explicitly round a number up or down, use ceil() or floor() function from math module.

Example:

# Round a number up
import math
x = math.ceil(4.5)
print(x)	# 5
# Round a number down
import math
x = math.floor(4.5)
print(x)	# 4