Format a float without trailing zeros in Python

avatar

Borislav Hadzhiev

Last updated: Sep 2, 2022

banner

Photo from Unsplash

Format a float without trailing zeros in Python #

To format a float without trailing zeros:

  1. Use the str() class to convert the float to a string.
  2. Use the str.rstrip() method to remove the trailing zeros.
  3. The result won't contain trailing zeros.
main.py
my_float = 59.4750000 # ✅ format float without trailing zeros (str.rstrip()) result = f'{str(my_float).rstrip("0").rstrip(".") if "." in str(my_float) else my_float}' print(result) # 👉️ '59.475' # -------------------------------------------------- # ✅ format float without trailing zeros (f-string) result = f'{my_float:g}' print(result) # 👉️ '59.475'

The first example uses the str.rstrip() method to format a float without trailing zeros.

The str.rstrip method returns a copy of the string with the provided trailing characters removed.

main.py
my_float = 59.4750000 print(str(my_float).rstrip('0')) # 👉️ '59.475'
We first strip trailing zeros, then try to strip the dot . if the decimal part only consisted of trailing zeros.
main.py
my_float = 59.0000 result = f'{str(my_float).rstrip("0").rstrip(".") if "." in str(my_float) else my_float}' print(result) # 👉️ '59'

The example also checks whether the string contains a dot, so we don't attempt to strip trailing zeros from numbers that don't have a decimal part, e.g. 2000 to 2.

We used a formatted string literal in the example.

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}.

Here is the same example without using a formatted string literal.

main.py
my_float = 59.4750000 string = str(my_float) result = string.rstrip( '0').rstrip('.') if '.' in string else string print(result) # 👉️ '59.475'

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

main.py
my_float = 59.4750000 result = f'{my_float:g}' print(result) # 👉️ '59.475'

The g format:

  1. removes insignificant trailing zeros from the number
  2. removes the decimal point if there are no remaining digits following it

However, the general format might format the result to scientific notation.

main.py
my_float = 1/123456 print(my_float) # 👉️ 8.100051840331778e-06 result = f'{my_float:g}' print(result) # 👉️ '8.10005e-06'

You can read more about it in the format specification mini-language documentation.

This is why it is generally more intuitive to use the rstrip() approach to strip the trailing zeros from the number.

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.