Python中的float()

Python float()函数 用于从数字或字符串返回浮点数。

null

语法: 浮动(x)

float()参数

该方法只接受一个参数,并且该参数也是可选的。让我们看看各种类型的参数,该方法接受:

一个数字: 可以是整数或浮点数。

一串:

  • 必须包含任何类型的数字。
  • 该方法将忽略任何左或右空格或新行。
  • 可以使用数学运算符。
  • 可以包含NaN、Infinity或inf(任何情况)

float()方法根据传递的参数可以返回的值

  • 如果传递了一个参数,则返回等效的浮点数。
  • 如果未传递任何参数,则该方法返回0.0。
  • 如果传递的任何字符串不是小数点或与上述任何情况不匹配,则将引发错误。
  • 如果传递的数字超出Python float的范围,则会生成OverflowerError。

Python示例中的float

示例1:float()在Python中的工作原理

Python3

# Python program to illustrate
# Various examples and working of float()
# for integers
print ( float ( 21.89 ))
# for floating point numbers
print ( float ( 8 ))
# for integer type strings
print ( float ( "23" ))
# for floating type strings
print ( float ( "-16.54" ))
# for string floats with whitespaces
print ( float ( "     -24.45   " ))
# for inf/infinity
print ( float ( "InF" ))
print ( float ( "InFiNiTy" ))
# for NaN
print ( float ( "nan" ))
print ( float ( "NaN" ))
# Error is generated at last
print ( float ( "Geeks" ))


输出:

21.898.023.0-16.54-24.45infinfnannan

所有行都正确执行,但最后一行将返回错误:

Traceback (most recent call last):  File "/home/21499f1e9ca207f0052f13d64cb6be31.py", line 25, in     print(float("Geeks"))ValueError: could not convert string to float: 'Geeks'

示例2:用于无穷大和Nan的float()

Python3

# Python program to illustrate
# Various examples and working of float()
# for inf/infinity
print ( float ( "InF" ))
print ( float ( "InFiNiTy" ))
# for NaN
print ( float ( "nan" ))
print ( float ( "NaN" ))


输出:

infinfnannan

示例3:在Python中将整数转换为浮点

Python3

# python code to convert int
# float
number = 90
result = float (number)
print (result)


输出:

90.0

实例 4:在Python中将字符串转换为浮点

Python3

# python code to convert string
# to float
string = "90"
result = float (string)
print (result)


输出:

90.0

例5:P ython float()异常

Python3

number = "geeks"
try :
print ( float (number))
except ValueError as e:
print (e)


输出:

could not convert string to float: 'geeks'
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享