Home »
Python
Parse a string to float in Python (float() function)
Python float() function example: Here, we are going to learn how to convert a given string value to the float value in Python?
Submitted by IncludeHelp, on March 31, 2019
Given a string value (that contains float value) and we have to convert it into float value in Python.
To convert a string value to the float, we use float() function.
Python float() function
float() function is a library function in python, it is used to convert a given string or integer value to the float value.
Syntax:
float(string_value/integer_value)
Example:
Input:
str = "10.23"
print(float(str))
Output:
10.23
Input:
str = "1001"
print(float(str))
Output:
1001.0
Python code to convert string to the float value
# python code to demonstrate example of
# float() function
str1 = "10.23"
str2 = "1001"
# printing str1 & str2 types
print("type of str1: ", type(str1))
print("type of str2: ", type(str2))
# converting to float value
val1 = float(str1)
val2 = float(str2)
# printing types and values of val1 & val2
print("type of val1: ", type(val1))
print("type of val2: ", type(val2))
print("val1 = ", val1)
print("val2 = ", val2)
Output
type of str1: <class 'str'>
type of str2: <class 'str'>
type of val1: <class 'float'>
type of val2: <class 'float'>
val1 = 10.23
val2 = 1001.0
ADVERTISEMENT
ADVERTISEMENT