📜  在 Python3 中将字符串转换为双精度

📅  最后修改于: 2022-05-13 01:54:28.954000             🧑  作者: Mango

在 Python3 中将字符串转换为双精度

给定一个字符串,我们的任务是将其转换为双精度。由于 double 数据类型允许数字具有非整数值。所以字符串到double的转换和字符串到float的转换是一样的

这可以通过这两种方式实现

1) 使用 float() 方法

Python3
str1 = "9.02"
print("This is the initial string: " + str1)
 
# Converting to double
str2 = float(str1)
print("The conversion of string to double is", str2)
 
str2 = str2+1
print("The converted string to double is incremented by 1:", str2)


Python3
from decimal import Decimal
 
 
str1 = "9.02"
print("This is the initial string: " + str1)
 
# Converting to double
str2 = Decimal(str1)
print("The conversion of string to double is", str2)
 
str2 = str2+1
print("The converted string to double is incremented by 1:", str2)


输出:

This is the initial string: 9.02
The conversion of string to double is 9.02
The converted string to double is incremented by 1: 10.02

2)使用decimal()方法:由于我们只想要一个带有十进制值的数字的字符串,因此也可以使用此方法

Python3

from decimal import Decimal
 
 
str1 = "9.02"
print("This is the initial string: " + str1)
 
# Converting to double
str2 = Decimal(str1)
print("The conversion of string to double is", str2)
 
str2 = str2+1
print("The converted string to double is incremented by 1:", str2)

输出:

This is the initial string: 9.02
The conversion of string to double is 9.02
The converted string to double is incremented by 1: 10.02