Convert Python String to Float datatype
Last Updated :
17 Aug, 2020
Let us see how to convert a string object into a float object. We can do this by using these functions :
Method 1: Using float()
str1 = "9.02"
print ( "The initial string : " + str1)
print ( type (str1))
str2 = float (str1)
print ( "\nThe conversion of string to float is " , str2)
print ( type (str2))
str2 = str2 + 1
print ( "The converted string to float is incremented by 1 : " , str2)
|
Output :
The initial string : 9.02
<type 'str'>
The conversion of string to float is 9.02
<type 'float'>
The converted string to float is incremented by 1 : 10.02
Method 2: Using decimal()
: Since we only want a string with a number with decimal values this method can also be used.
from decimal import Decimal
str1 = "9.02"
print ( "The initial string : " + str1)
print ( type (str1))
str2 = Decimal(str1)
print ( "\nThe conversion of string to float is " , str2)
print ( type (str2))
str2 = str2 + 1
print ( "The converted string to float is incremented by 1 : " , str2)
|
Output :
The initial string : 9.02
<type 'str'>
The conversion of string to float is 9.02
<type 'float'>
The converted string to float is incremented by 1 : 10.02
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...