round() Function in Python

Python round() Function

The round() function in Python is used to round a number to a specified number of decimal places or to the nearest integer. It takes one or two arguments:

  • number (required): The number that you want to round.
  • ndigits (optional): The number of decimal places to which you want to round the number. If ndigits is not provided, the number will be rounded to the nearest integer.

Syntax:

rounded_number = round(number, ndigits)

Rounding to the nearest integer:

num1 = 4.6
rounded_num1 = round(num1)  # Result: 5

Rounding to a specified number of decimal places:

num2 = 3.14159
rounded_num2 = round(num2, 2)  # Result: 3.14

Negative ndigits rounds the number to the nearest 10, 100, etc.:

num3 = 1234
rounded_num3 = round(num3, -2)  # Result: 1200

Rounding large numbers:

num4 = 9876543210
rounded_num4 = round(num4, -4)  # Result: 9877000000

It's important to note that the round() function uses the "round half to even" strategy (also known as "rounding to nearest, ties to even"). This means that if the digit after the specified decimal place is exactly 5, the function will round to the nearest even number. For example:

num5 = 2.5
rounded_num5 = round(num5)  # Result: 2

num6 = 3.5
rounded_num6 = round(num6)  # Result: 4

Keep this behavior in mind when working with the round() function.