Friday, December 12, 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

1 COMMENT

Most Popular

Dominic
32445 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11951 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12028 POSTS0 COMMENTS
Shaida Kate Naidoo
6947 POSTS0 COMMENTS
Ted Musemwa
7198 POSTS0 COMMENTS
Thapelo Manthata
6893 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS