How to convert string to float in Python
In this article, you are going to learn about how to convert string to float in Python.
String and float both are considered as the data types in the Python programming language. The string data type is used to represent those data that are text-based. On the other hand, the float is that kind of data type that is used to represent number-based data with a point. In python, floating-point numbers are considered as the 64bit floating point. Sometimes, you need to convert a string type data into a floating number, and to do so you may use the float() method that is available in python. In this article, we will discover how you can convert a string in the float by using the float() and also see some other approaches to do so.
float() method
The float() method is used to convert a string into floating-point numbers and this method is widely used in the python programming language. It only accepts one parameter and passing the string value into this parameter you may easily convert a string to a floating-point number. See the below code example:
math_score = '87.40'
print(type(math_score))
# Using float() method
str_to_float = float(math_score)
print(type(str_to_float))
# Output:
# <class 'str'>
# <class 'float'>
Here, you can see that the type of our value was string at first and we are successfully being able to convert it into a floating-point number by using the float() method. To check the type of the variable we are using the type() method that shows us the type of the particular variable.
Numpy library
You can convert a string into the floating-point number by using the float() method smoothly. Besides this method, there is another way of performing this action and that is using the Numpy library. This library is basically used to perform high mathematical operations. But let’s see an example of using it in a simple way.
import numpy as np
result = np.array(['65.89','92.65','87.33','79.90'])
print(result)
# Using numpy library
str_to_float = result.astype(float)
print(str_to_float)
# Output:
# ['65.89' '92.65' '87.33' '79.90']
# [65.89 92.65 87.33 79.9 ]
Here, we have first imported the numpy library in our program and then convert an array of strings in the floating-point numbers array. You can see that in the output. But it was always recommended to use the float() method for converting a string into a floating-point number and you may perform almost every task that is related to converting with this method. Finally, these are some useful approaches for converting a string into the floating-point number in the python programming language.