Convert String to Float
Convert String to Float
To convert string to floating-point number in Python, we can use the float() built-in function. Pass the string as argument to float() and it returns a float value.
In this tutorial, we shall go through some of the example programs that convert a string to floating-point number.
Examples
1. Convert given string to a float value
In this example, we will take a string in variable a
, print it and its datatype, then convert it to float.
Python Program
a = '3.14'
print('Before Conversion')
print(a, 'is of type:', type(a))
a = float(a)
print('After Conversion')
print(a, 'is of type:', type(a))
Output
Before Conversion
3.14 is of type: <class 'str'>
After Conversion
3.14 is of type: <class 'float'>
2. Negative scenario - Invalid string to convert to a float value
If the input string is not a valid floating-point value, then float() with the given string raises ValueError as shown in the following program.
Python Program
a = '3.14AB'
print('Before Conversion')
print(a, 'is of type:', type(a))
a = float(a)
print('After Conversion')
print(a, 'is of type:', type(a))
Output
Before Conversion
3.14AB is of type: <class 'str'>
Traceback (most recent call last):
File "/Users/pythonexamples/example.py", line 5, in <module>
a = float(a)
ValueError: could not convert string to float: '3.14AB'
Summary
In this tutorial of Python Examples, we learned how to convert a string to floating-point number using float() builtin function.