Convert String to Float

To convert a String to Floating-point number in Python, use float() builtin function. flaot() function can take a string as argument and return a floating-point equivalent of the given argument.

The syntax to convert a string x to floating-point number is

</>
Copy
float(x)

Examples

In the following example, we take a string in variable x, and convert it into floating-point number using float() function. We shall print the float output to console, and to confirm the datatype of the variable output, we shall print its datatype as well using type().

Python Program

</>
Copy
x = '3.14'
output = float(x)
print(output)
print(type(output))

Output

3.14
<class 'float'>

Negative Scenarios

If there are any invalid characters for a floating-point number, then float() function raises ValueError as shown in the following.

The character 'a' is not valid to be in an integer. Therefore, trying to convert '125a' to integer by int() function raises ValueError.

Python Program

</>
Copy
x = '3.14 A'
output = float(x)
print(output)
print(type(output))

Output #1

Traceback (most recent call last):
  File "/Users/tutorialkart/python/example.py", line 2, in <module>
    output = float(x)
ValueError: could not convert string to float: '3.14 A'

To handle this error, we may use try-except around our code.

Python Program

</>
Copy
x = '3.14 A'
try:
    output = float(x)
    print(output)
    print(type(output))
except ValueError:
    print('Cannot convert to float')

Output

Cannot convert to float

Conclusion

In this Python Tutorial, we learned how to convert a string into a floating-point number, and also handle if the string cannot be converted to a valid float.