當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python3 String轉Double用法及代碼示例

給定一個字符串,我們的任務是將其轉換為雙精度。由於雙精度數據類型允許數字具有非整數值。因此,字符串到雙精度的轉換與字符串到浮點的轉換相同

可以通過這兩種方式實現

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)

輸出:

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

相關用法


注:本文由純淨天空篩選整理自shivanshsaxena1大神的英文原創作品 Convert String to Double in Python3。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。