給定一個字符串,我們的任務是將其轉換為雙精度。由於雙精度數據類型允許數字具有非整數值。因此,字符串到雙精度的轉換與字符串到浮點的轉換相同
可以通過這兩種方式實現
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
相關用法
- Python String format()用法及代碼示例
- Python abs()用法及代碼示例
- Python any()用法及代碼示例
- Python all()用法及代碼示例
- Python ascii()用法及代碼示例
- Python bin()用法及代碼示例
- Python bool()用法及代碼示例
- Python bytearray()用法及代碼示例
- Python callable()用法及代碼示例
- Python bytes()用法及代碼示例
- Python chr()用法及代碼示例
- Python compile()用法及代碼示例
- Python classmethod()用法及代碼示例
- Python complex()用法及代碼示例
- Python delattr()用法及代碼示例
- Python dict()用法及代碼示例
- Python dir()用法及代碼示例
- Python divmod()用法及代碼示例
- Python enumerate()用法及代碼示例
- Python staticmethod()用法及代碼示例
- Python filter()用法及代碼示例
- Python eval()用法及代碼示例
- Python float()用法及代碼示例
- Python format()用法及代碼示例
- Python frozenset()用法及代碼示例
注:本文由純淨天空篩選整理自shivanshsaxena1大神的英文原創作品 Convert String to Double in Python3。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。