Check if a string can be converted to a float in Python

avatar

Borislav Hadzhiev

Last updated: Jul 12, 2022

banner

Photo from Unsplash

Check if a string can be converted to a float in Python #

To check if a string can be converted to a float:

  1. Wrap the call to the float() class in a try/except block.
  2. If the try block runs successfully, the string can be converted to a float.
  3. If the except block runs, the string cannot be converted to a float.
main.py
my_str = '3.456' try: result = float(my_str) print(result) # 👉️ 3.456 except ValueError: print('Value cannot be converted to a float')

We used a try/except statement to check if a string can be converted to a float.

If the try block runs successfully, the string can be converted to a float.

If trying to convert the string to a float() raises a ValueError, the string cannot be converted to a float.
main.py
my_str = 'abc1.23' try: result = float(my_str) print(result) except ValueError: # 👇️ this runs print('Value cannot be converted to a float')

You can also extract the logic into a reusable function.

main.py
def can_convert_to_float(string): try: result = float(string) print(result) return True except ValueError: return False print(can_convert_to_float('123')) # 👉️ True print(can_convert_to_float('1.23')) # 👉️ True print(can_convert_to_float('a.bc')) # 👉️ False print(can_convert_to_float('.5')) # 👉️ True if can_convert_to_float('3.14'): # 👇️ this runs print('String can be converted to a float ✅') else: print('String cannot be converted to a float ⛔️')

If the try block succeeds, the function returns True.

If calling the float() class with the string fails, a ValueError is raised and the function returns False.

Using a try/except statement in this manner is commonly known as "asking for forgiveness rather than permission".

We pass the string to the float() class not knowing whether the conversion will be successful, and if a ValueError error is raised, we handle it in the except block.

If you want to silence/ignore the error when it's raised, use the pass statement.

main.py
my_str = 'ab.cd' try: result = float(my_str) print(result) except ValueError: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

main.py
class Employee: pass
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.