Python float()

float() 方法将数字或字符串转换为浮点数。

示例

int_number = 25

# convert int to float float_number = float(int_number)
print(float_number) # Output: 25.0

float() 语法

float() 的语法是

float([x])

float() 参数

float() 方法接受一个参数

  • x (可选) - 需要转换为浮点数的数字或字符串
    如果它是字符串,字符串应包含小数点。
参数类型 用法
浮点数 用作浮点数
整数 用作整数
字符串 必须包含小数。前导和尾随的空格会被移除。可选使用"+"、"-"符号。可以包含NaNInfinityinf(小写或大写)。

float() 返回值

float() 方法返回

  • 如果传入参数,则返回等效的浮点数
  • 如果未传入参数,则返回 0.0
  • 如果参数超出 Python 浮点数的范围,则抛出 OverflowError 异常

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

# for integers
print(float(10))

# for floats
print(float(11.22))

# for string floats
print(float("-13.33"))
# for string floats with whitespaces
print(float(" -24.45\n"))
# string float error
print(float("abc"))

输出

10.0
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'

示例 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

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战