📜  Python float()

📅  最后修改于: 2020-09-20 04:03:34             🧑  作者: Mango

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

float()的语法为:

float([x])

float()参数

float()方法采用一个参数:

  1. x(可选)-需要转换为浮点数的数字或字符串。如果是字符串,则该字符串应包含小数点
Different parameters with float()
Parameter Type Usage
Float number Use as a floating number
Integer Use as an integer
String Must contain decimal numbers. Leading and trailing whitespaces are removed. Optional use of “+”, “-” signs. Could contain NaN, Infinity, inf (lowercase or uppercase).

从float()返回值

float()方法返回:

  1. 传递参数时的等效浮点数
  2. 如果没有传递参数,则为0.0
  3. 如果参数超出Python float范围,则发生OverflowError异常

示例1:float()如何在Python?

# 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