Skip to content

Python round() Function

How to use Python's built-in round() function to round numbers to integers or specified decimal places, including handling edge cases like banker's rounding and floating-point precision issues.

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)

round() Parameters

Python round() function parameters:

Parameter Condition Description
number Required The number to be rounded.
ndigits Optional Number of decimals up to which the given number is rounded. Defaults is 0.

round() Return Value

Python round() function returns:

  • nearest integer to the given number if ndigits is not provided
  • number rounded off to the ndigits digits if ndigits is provided

Examples

Example 1: Basic Usage of round() function

print(round(10))   # Output: 10

print(round(10.7)) # Output: 11

print(round(5.5)) # Output: 6

output:

10
11
6

Example 2: Rounding to Specified Decimal Places

You can specify the number of decimal places with the ndigits parameter.

For example, let's round to 2 decimal places:

print(round(2.665, 2)) # Output: 2.67
print(round(2.675, 2)) # Output: 2.67

output:

2.67
2.67

Example 3: Rounding to Even (Banker's Rounding)

The round() function rounds to the nearest integer by default. However, it's important to note that round() uses "round half to even" (also known as "bankers' rounding") for rounding, which means that when a number is exactly halfway between two others, it rounds to the nearest even number.

For example:

print(round(4.4))  # Output: 4
print(round(4.5))  # Output: 4
print(round(4.6))  # Output: 5

print(round(5.4))  # Output: 5
print(round(5.5))  # Output: 6
print(round(5.6))  # Output: 6

output:

4
4
5
5
6
6

Example 4: High-precision rounding with Decimal module and round() function

If you need precision, consider to use the decimal module, which is designed for floating-point arithmetic. For example:

from decimal import Decimal

num = 2.675
print(round(num, 2)) # Output: 2.67

num = Decimal('2.675')
print(round(num, 2)) # Output: 2.68

output:

2.67
2.68

Example 5: Round with negative ndigits parameter

The ndigits parameter can be negative.

If it is negative, it allows you to for example round numbers to ten's or hundred's.

For example, let's rounds to ten's:

print(round(34, -1))     # Output: 30
print(round(246, -1))    # Output: 250
print(round(456, -1))    # Output: 460

output

30
250
460

For example, let's rounds to hundred's:

print(round(34, -2))     # Output: 0
print(round(246, -2))    # Output: 200
print(round(456, -2))    # Output: 500

output

0
200
500

Example 6:

Navigation