Python round() function
Round a number to a given number of decimal places.
Syntax
round(number, ndigits=None)
With no ndigits it returns a whole number (int). Exact halves round to the nearest even number ("banker's rounding"), so round(2.5) is 2. To display a fixed number of decimals, an f-string such as f"{x:.2f}" is often better.
Parameters
| number | the number to round |
| ndigits | decimal places (can be negative) |
Return value
int if ndigits is omitted, otherwise a float
Example
Code
print(round(3.14159, 2)) print(round(7.6), round(-7.6)) print(round(2.5), round(3.5)) # halves go to the even number print(round(1234, -2)) # to the nearest hundred x = 2.0 print(f"{x:.2f}") # for display: always 2 decimals
Output
3.14 8 -8 2 4 1200 2.00
Related
Learn it step by step in the free lesson Values, Variables & Numbers, with exercises that check your answers.