22. Python float()

发布时间:2023-12-08

Python float()

更新:2022-07-24 11:11 float() 方法从给定的数字或字符串中返回相应的浮点数。

float([x])

其中 x 可以是需要转换的数字或字符串。

float() 参数:

它接受需要返回浮点数的单个参数、数字或字符串。

参数 描述 必需/可选
浮点 用作浮点数 可选
整数 用作整数 可选
字符串 它包含十进制数。前导空格和尾随空格被删除。可选使用 +- 符号。可以包含 NaNInfinityinf(小写或大写)。 可选

float() 返回值

输入 返回值
如果一个参数 等效浮点数
如果没有参数 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