float()
方法從給定的數字或字元串中返回相應的浮點數。
**float([x])**#Where **x** can be a number or string that needs to convert
浮點()參數:
它接受需要返回浮點數的單個參數、數字或字元串
參數 | 描述 | 必需/可選 |
---|---|---|
浮動 | 用作浮點數 | 可選擇的 |
整數 | 用作整數 | 可選擇的 |
線 | 它包含十進位數。前導空格和尾隨空格被刪除。可選使用「+」、「-」符號。可以包含 NaN、Infinity、inf(小寫或大寫)。 | 可選擇的 |
浮點()返回值
| 投入 | 返回值 |
| 如果一個論點 | 等效浮點數 |
| 如果沒有爭論 | 0.0 |
| 該參數超出了 Python 浮點的範圍 | OverflowError 異常 |
Python 中float()
方法的示例
示例 Python 中float()
的工作原理?
# for integers
print(float(20))
# for floats
print(float(12.33))
# for string floats
print(float("-15.34"))
# for string floats with whitespaces
print(float(" -32.25\n"))
# string float error
print(float("abcd"))
輸出:
20.0
13.33
-15.34
-32.25
ValueError: could not convert string to float: 'abcd'
例 2: float()
表示無窮大,Nan(不是數字)?
# for NaN
print(float("nan"))
print(float("NaN"))
# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))
輸出:
nan
nan
inf
inf
inf
inf
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/303474.html