Wednesday, October 1, 2025
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

Most Popular

Dominic
32330 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11926 POSTS0 COMMENTS
Shaida Kate Naidoo
6815 POSTS0 COMMENTS
Ted Musemwa
7078 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6774 POSTS0 COMMENTS