将Python字符串转换为浮点数据类型
让我们看看如何将字符串对象转换为浮点对象。我们可以通过使用这些函数来做到这一点:
- 漂浮()
- 十进制()
方法一:使用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)
输出 :
The initial string : 9.02
The conversion of string to float is 9.02
The converted string to float is incremented by 1 : 10.02
方法 2:使用decimal()
:由于我们只想要一个带有十进制值的数字的字符串,因此也可以使用此方法。
# 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)
输出 :
The initial string : 9.02
The conversion of string to float is 9.02
The converted string to float is incremented by 1 : 10.02