
float()方法从数字或字符串中返回浮点数。
float()的语法为:
float([x])
float()参数
float()方法采用一个参数:
- x(可选) -需要转换为浮点数的数字或字符串。 
 如果是字符串,则该字符串应包含小数点
| 参数类型 | 用法 | 
|---|---|
| Float number | 用作浮点数 | 
| Integer | 用作整数 | 
| String | 必须包含十进制数字。 前导和尾随空格被删除。 可选使用“ +”,“-”符号。 可以包含NaN,Infinity,inf(小写或大写)。 | 
float()返回值
float()方法返回:
- 传递参数时的等效浮点数 
- 如果没有传递参数,则为0.0 
- 如果参数超出Python float的范围,则会发生OverflowError异常 
示例1:float()如何在Python中工作?
# 参数为整数
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: could not convert string to float: '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
