跳到主要内容

Python float() 函数

float() 方法从一个数字或字符串中返回一个浮点数。

示例

int_number = 25

# 将整数转换为浮点数
float_number = float(int_number)
print(float_number)

# 输出: 25.0

float() 语法

float() 的语法是:

float([x])

float() 参数

float() 方法接受一个参数:

  • x(可选) - 需要转换为浮点数的数字或字符串 如果是字符串,字符串中应该包含小数点
参数类型使用
浮点数作为浮点数使用
整数作为整数使用
字符串必须包含小数数字。会去除前后空白。可选使用"+"、"-"符号。可能包含 NaNInfinityinf(大小写不限)。

float() 返回值

float() 方法返回:

  • 如果传递了参数,则返回等价的浮点数
  • 如果没有传递参数,则返回 0.0
  • 如果参数超出了 Python 浮点数的范围,则抛出 OverflowError 异常

示例 1:Python 中的 float() 如何工作?

# 对于整数
print(float(10))

# 对于浮点数
print(float(11.22))

# 对于字符串浮点数
print(float("-13.33"))

# 对于带有空白的字符串浮点数
print(float(" -24.45\n"))

# 字符串浮点数错误
print(float("abc"))

输出

10.0
11.22
-13.33
-24.45
ValueError: 无法将字符串转换为浮点数: 'abc'

示例 2:float() 对于无穷大和 NaN(非数字)的处理?

# 对于 NaN
print(float("nan"))
print(float("NaN"))

# 对于 inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

输出

nan
nan
inf
inf
inf
inf