Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Convert Python String to Float datatype

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Let us see how to convert a string object into a float object. We can do this by using these functions :

  • float()
  • decimal()

Method 1: Using float()




# declaring a string
str1 = "9.02"
print("The initial string : " + str1)
print(type(str1)) 
  
# converting into float
str2 = float(str1)
print("\nThe conversion of string to float is ", str2)
print(type(str2)) 
  
# performing an operation on the float variable
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.




# importing the module
from decimal import Decimal
  
# declaring a string
str1 = "9.02"
print("The initial string : " + str1)
print(type(str1)) 
  
# converting into float
str2 = Decimal(str1)
print("\nThe conversion of string to float is ", str2)
print(type(str2)) 
  
# performing an operation on the float variable
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

My Personal Notes arrow_drop_up
Last Updated : 17 Aug, 2020
Like Article
Save Article
Similar Reads
Related Tutorials