Python round()

The round() function rounds a number.

Example

number = 13.46

# round 13.46 to the nearest integer rounded_number = round(number)
print(rounded_number) # Output: 13

round() Syntax

round(number, ndigits)

round() Parameters

The round() function takes two parameters:

  • number - the number to be rounded.
  • ndigits (optional) - number up to which the given number is rounded; defaults to 0.

round() Return Value

The round() function returns the

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

Example 1: How round() works in Python?

# for integers
print(round(10))
# for floating point
print(round(10.7))
# even choice
print(round(5.5))

Output

10
11
6

Here,

  • round(10): rounds the integer to 10
  • round(10.7): rounds the float 10.7 to nearest integer, 11.
  • round(5.5): rounds the float 5.5 to 6.

Example 2: Round a number to the given number of decimal places

print(round(2.665, 2))
print(round(2.675, 2))

Output

2.67
2.67

When the decimal 2.675 is converted to a binary floating-point number, it's again replaced with a binary approximation, whose exact value is:

2.67499999999999982236431605997495353221893310546875

Due to this, it is rounded down to 2.67.

Note: The behavior of round() for floats can be surprising. Notice round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it's a result of the fact that most decimal fractions can't be represented exactly as a float.

If you're in a situation where this precision is needed, consider using the decimal module, which is designed for floating-point arithmetic:

from decimal import Decimal

# normal float
num = 2.675
print(round(num, 2))
# using decimal.Decimal (passed float as string for precision) num = Decimal('2.675')
print(round(num, 2))

Output

2.67
2.68

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges