Add zeros to a float after the decimal in Python

avatar

Borislav Hadzhiev

Last updated: Jun 22, 2022

banner

Photo from Unsplash

Add zeros to a float after the decimal in Python #

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.

main.py
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 function takes a value and a format specifier and converts the value to a formatted representation according to the provided format specifier.

The f type in the format specifier stands for fixed-point notation.

main.py
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.

main.py
my_float = 3.00000000 print(my_float) # 👉️ 3.0

An alternative approach is to use a formatted string literal.

main.py
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.

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 = 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'
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.