float() 方法从给定数字或字符串返回相应的浮点数。
float([x]) #Where x can be a number or string that needs to convert
它接受一个参数,即需要返回浮点数的数字或字符串
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 浮点数 | 用作浮点数 | 可选 |
| 整型 | 用作整数 | 可选 |
| 字符串 | 它包含小数。前导和尾随空格被移除。可选使用“+”、“-”符号。可以包含 NaN、Infinity、inf(小写或大写)。 | 可选 |
| 输入 | 返回值 |
|---|---|
| 如果有一个参数 | 等效的浮点数 |
| 如果没有参数 | 0.0 |
| 参数超出 Python 浮点数范围 | OverflowError 异常 |
# 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'
# 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