To convert String to float in Python, we are using the float() method that returns a floating point value of any number or a string.
The float() method is a built-in method so we don't need to import any library. We just need to pass the string (string that we want to convert) to the float() method and get a string object as a result.
Here, we have some examples that elaborate on the conversion process of string to a float type. At the end of the topic, we have one more example that performs float to string conversion which is just reverse of that.
Let's see the example here to understand the conversion of string to float and vice versa.
Here, we have a variable 'a' that holds a string value and we are using float() method to convert this variable to a float type value. Here, we used the type() method for checking the type of a variable before and after conversion.
# Take a string
a = "10.50"
print(a)
print(type(a))
# Convert string to float
a = float(a)
print(a)
print(type(a))
Output:
10.50
<class 'str'>
10.5
<class 'float'>
Note: The type() method is used to check the type of a variable or an object in Python.
In the above examples, we learned string to float conversion. Now, we will convert float to string by using the str() method. The str() method returns a string object as a result. We can use it to get a string from an object like int, float, etc. The type() method returns the type of a variable or object.
# Take a float
a = 10.50
print(a)
print(type(a))
# Convert float to string
a = str(a)
print(a)
print(type(a))
Output:
10.5
<class 'float'>
10.5
<class 'str'>
Well, in this topic, we learned to convert string to float and vice versa. We used float() and str() functions to convert string to float and float to string respectivly. We have provided examples to understand the conversion easily.
If we missed something, you can suggest us at - info.javaexercise@gmail.com