Borislav Hadzhiev
Last updated: Jul 13, 2022
Check out my new book
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.
# ✅ 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:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal, the number should have after the operation (optional) |
round
function returns the number rounded to ndigits
precision after the decimal point.If ndigits
is omitted, the function returns the nearest integer.
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.
my_float = 7.456789 my_str_3 = f'{my_float:.3f}' print(my_str_3) # 👉️ '7.457'
f
.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.
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.