Thursday, February 19, 2026
HomeLanguagesConvert Python String to Float datatype

Convert Python String to Float datatype

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
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS