python

String to Float conversion in python

Python offers a built-in method for converting strings to Floats easily. The built-in function is float() which converts numbers or numerical data contained within strings into floating-point numbers.

value = "190"

result = float(value)
print(result)
# -> 190.0

When working with data that is coming from strings, you might need to convert them to floats for further processing. This code snippet shows you how to easily convert string to float in python.

The string could be an input value from a user or a value returned by a sensor or some other device. We can do this conversion using the float() function in python.

Convert String using python float() function

string to float python function will convert a number from string to float. If it is not a number it will throw an error.

The basic syntax to parse a value to float is below

float(value)

Here, value is a parameter that is to be converted to float. If nothing is passed as the value parameter it will return 0.0

Examples of str to float

I am sure that you have found a string value in your program and want to convert it to float. Here are some more examples

val1 = float("20")
# -> 20.0

val2 = float("12.06")
# -> 12.06

val3 = float("-23.7")
# -> -23.7

val4 = float("NaN")
# -> nan

val5 = float("InF")
# -> inf

Whats will happen if the string does not contain numbers but alphabetical characters

The value that you are passing as a parameter in the float() function must contain only numeric values. If it contains alphabetical characters then it will not return anything and throw an error. Below is an example of that.

value = "hello"
result = float(value)

The above code will throw below error as the value parameter that we are passing in the float() method does not contain numbers.

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    val1 = float("hello")
ValueError: could not convert string to float: 'hello'

Handle ValueError using exception handling

If you want to handle the ValueError exception caused by the python float() method, you can use exception handling in python.

value = "devsheet"

try:
  result = float(value)
except Exception as e:
  print("Could not convert str to float")
  
# -> Could not convert str to float

You can also check Nan Values using the float() method with the use of exception handling. You can read more about it below link.

Check NaN using float() method in python

Was this helpful?