Borislav Hadzhiev
Wed Jun 22 2022·1 min read
Photo by Christoffer Engström
Use the format()
function to add zeros to a float after the decimal, e.g.
result = format(my_float, '.3f')
. The function will format the number with
exactly N digits following the decimal point.
my_float = 3.0 result = format(my_float, '.3f') print(result) # 👉️ '3.000' print(type(result)) # 👉️ <class 'str'>
We used the format function to add zeros to a float after the decimal.
The f
type in the format specifier stands for fixed-point notation.
my_float = 3.0 result_1 = format(my_float, '.3f') print(result_1) # '3.000' result_2 = format(my_float, '.4f') print(result_2) # '3.0000' result_3 = format(my_float, '.6f') print(result_3) # '3.000000'
Notice that the value the format()
function returns is a string.
This is necessary because Python doesn't keep any non-significant, trailing zeros around.
my_float = 3.00000000 print(my_float) # 👉️ 3.0
An alternative approach is to use a formatted string literal.
my_float = 3.0 result = f'{my_float:.3f}' print(result) # 👉️ '3.000'
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with 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 = 3.2 result_1 = f'{my_float:.3f}' print(result_1) # 👉️ '3.200' result_2 = f'{my_float:.5f}' print(result_2) # 👉️ '3.20000' result_3 = f'{my_float:.6f}' print(result_3) # 👉️ '3.200000'