Using f-strings to format floats to N digits after decimal in Python

avatar

Borislav Hadzhiev

Last updated: Sep 1, 2022

banner

Photo from Unsplash

Using f-strings to format floats to N digits after decimal in Python #

Use an expression to format floats to N digits after the decimal using f-strings, e.g. result = f'{my_float:.2f}'. The formatted string literal can be passed an expression where we can specify the number of decimal places the number should get formatted to.

main.py
my_float = 3.368923489 # ✅ using f-string to format float to 2 decimal places result = f'{my_float:.2f}' print(result) # 👉️ '3.37' # ------------------------------------ # ✅ using f-string to format float to 3 decimal places number_of_decimals = 3 result = f'{my_float:.{number_of_decimals}f}' print(result) # 👉️ '3.369' # ------------------------------------ # ✅ using f-string to format list of floats to 2 decimal places list_of_floats = [4.932493, 6.238482, 9.4823982] result = [f'{num:.2f}' for num in list_of_floats] print(result) # 👉️ ['4.93', '6.24', '9.48']
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

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

Formatted string literals also enable us to use the format-specific mini-language in expression blocks.

main.py
my_float = 3.368923489 print(f'{my_float:.2f}') # 👉️ 3.37 print(f'{my_float:.3f}') # 👉️ 3.369

The digit after the period is the number of decimal places the float should have.

If you have the number of decimal places stored in a variable, wrap it in curly braces in the f-string.

main.py
my_float = 3.368923489 number_of_decimals = 3 result = f'{my_float:.{number_of_decimals}f}' print(result) # 👉️ '3.369'

You can also use an f-string to format a floating-point number to a fixed width.

main.py
my_float = 3.368923489 result = f'{my_float:5.2f}' print(repr(result)) # 👉️ ' 3.37'

The digit right after the colon is the width to format the number to.

The string gets left-padded with spaces to format the float to the specified length.

If you need to print a list of floating-point numbers to 2 decimal places, use a list comprehension.

main.py
list_of_floats = [4.932493, 6.238482, 9.4823982] result = [f'{num:.2f}' for num in list_of_floats] print(result) # 👉️ ['4.93', '6.24', '9.48']

We used a list comprehension to iterate over the list of floating-point numbers.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use a formatted string literal to format the current float to 2 decimal places and return the result.

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.