Round a float to N decimals in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Check out my new book

Round a float to N decimals in Python #

Use the round() function to round a float to N decimals, e.g. result = round(my_float, 3). The round() function takes ndigits as its second argument and rounds the number to N digits precision after the decimal point.

main.py
# ✅ Round float to N decimals my_float = 7.456789 result_1 = round(my_float, 1) print(result_1) # 👉️ 7.5 result_2 = round(my_float, 2) print(result_2) # 👉️ 7.46 result_3 = round(my_float, 3) print(result_3) # 👉️ 7.457 # ---------------------------------- # ✅ print a float rounded to N decimals my_float = 7.456789 my_str_1 = f'{my_float:.1f}' print(my_str_1) # 👉️ '7.5' my_str_2 = f'{my_float:.2f}' print(my_str_2) # 👉️ '7.46' my_str_3 = f'{my_float:.3f}' print(my_str_3) # 👉️ '7.457'

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe number of digits after the decimal, the number should have after the operation (optional)
The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

main.py
my_float = 7.456789 print(round(my_float)) # 👉️ 7 print(round(my_float, 1)) # 👉️ 7.5 print(round(my_float, 2)) # 👉️ 7.46 print(round(my_float, 3)) # 👉️ 7.457

If you need to print a floating-point number rounded to N decimal places, use a formatted string literal.

main.py
my_float = 7.456789 my_str_3 = f'{my_float:.3f}' print(my_str_3) # 👉️ '7.457'
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

We are also able to use the format specification mini-language in expressions in f-strings.

main.py
my_float = 7.456789 my_str_1 = f'{my_float:.1f}' print(my_str_1) # 👉️ '7.5' my_str_2 = f'{my_float:.2f}' print(my_str_2) # 👉️ '7.46' my_str_3 = f'{my_float:.3f}' print(my_str_3) # 👉️ '7.457'

The f character between the curly braces stands for fixed-point notation.

The character formats the number as a decimal number with the specified number of digits following the decimal point.

Use the search field on my Home Page to filter through my more than 3,000 articles.