Python中的float()

Float方法是python标准库的一部分,该标准库将数字或包含数字的字符串转换为float数据类型。当将字符串转换为浮点数有效时,有以下规则。

  • 该字符串中只能包含数字。

  • 数字之间的数学运算符也可以使用。

  • 该字符串可以表示NaN或inf

  • 开头和结尾的空白始终被忽略。

示例

下面的程序指示在应用float函数时如何返回不同的值。

n = 89
print(type(n))
f = float(n)
print(type(f))
print("input",7," with float function becomes ",float(7))
print("input",-21.6," with float function becomes ",float(-21.6))
print("input NaN, with float function becomes ",float("NaN"))
print("input InF, with float function becomes ",float("InF"))

输出结果

运行上面的代码给我们以下结果-

<class 'int'>
<class 'float'>
input 7 with float function becomes 7.0
input -21.6 with float function becomes -21.6
input NaN, with float function becomes nan
input InF, with float function becomes inf

在没有任何数值的情况下传递流会引发错误。

示例

print("input Tutorials, with float function becomes ",float("Tutorials"))

输出结果

运行上面的代码给我们以下结果-

Traceback (most recent call last):
   File "C:/xxx.py", line 18, in
      print("input Tutorials, with float function becomes ",float("Tutorials"))
ValueError: could not convert string to float: 'Tutorials'