How to Use the Python round() Function
Contents
In this article, you will learn how to use the Python round() function.
Python round() Function
The round() function in Python is used to round a number to a specified number of decimal places.
Syntax
Here is the syntax for using the round() function in Python:
round(number, ndigits)
Parameters
number
: The number to be rounded.ndigits
: The number of decimal places to round the number to. If ndigits is not specified, the number is rounded to the nearest integer.
Example
Here are some examples of using the round() function in Python:
# rounding a float to the nearest integer
x = 3.14159
print(round(x)) # Output: 3
# rounding a float to 2 decimal places
x = 3.14159
print(round(x, 2)) # Output: 3.14
# rounding a float to 4 decimal places
x = 3.14159
print(round(x, 4)) # Output: 3.1416
It’s important to note that the round() function follows the standard rounding rules. For example, if the first decimal place is 5 or greater, the number is rounded up; otherwise, it is rounded down.
Here are some additional things to keep in mind when using the round() function in Python:

Rounding with ndigits=0 will always round to the nearest integer, regardless of the decimal value of the number. For example:
# rounding a float to the nearest integer (ndigits = 0) x = 3.14159 print(round(x, 0)) # Output: 3 x = 3.7 print(round(x, 0)) # Output: 4

If ndigits is negative, the number is rounded to the left of the decimal point. For example:
# rounding a float to the nearest 10 (ndigits = 1) x = 35.6 print(round(x, 1)) # Output: 40 x = 33.2 print(round(x, 1)) # Output: 30

The round() function returns a float if the input number is a float. If the input number is an integer, the round() function returns an integer.
# rounding an integer x = 7 print(round(x)) # Output: 7 (int) # rounding a float x = 7.0 print(round(x)) # Output: 7 (float)
 If the input number is not a valid number (e.g., None, float(‘inf’), etc.), a TypeError will be raised.