Get the length of a Float in Python


Borislav Hadzhiev

Last updated: Jun 14, 2022


Photo from Unsplash

Get the length of a Float in Python #

To get the length of a float in Python:

  1. Use the str() class to convert the float to a string, e.g. result = str(my_float).
  2. Pass the string to the len() function, e.g. len(result).
  3. The len() function will return the length of the string.
my_float = 3.14 my_str = str(my_float) print(len(my_str)) # 👉️ 4 without_counting_decimal = len(my_str) - 1 print(without_counting_decimal) # 👉️ 3

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

This is why we had to convert the floating-point number to a string - we can't pass a float to the len() function as floats are not a sequence or a collection.

If you don't want to count the decimal, either subtract 1 from the result or replace it with an empty string.
my_float = 3.14 my_str = str(my_float) print(len(my_str)) # 👉️ 4 no_decimal_1 = len(my_str) - 1 print(no_decimal_1) # 👉️ 3 no_decimal_2 = len(my_str.replace('.', '')) print(no_decimal_2) # 👉️ 3

We used the str.replace() method to remove the decimal from the string by replacing it with an empty string.

If you need to handle a scenario where the number is negative, subtract 1 from the result.
my_float = 3.14 if my_float < 0: result = len(str(my_float)) - 1 else: result = len(str(my_float)) print(result) # 👉️ 4

We check if the float is less than 0, and if it is, we subtract 1 from its length to account for the minus - sign.

You can also use a formatted string literal to get the length of a float.
my_float = 3.14 result = len(f'{my_float}') print(result) # 👉️ 4

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

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.