Python中的浮点()
Python float()函数用于从数字或字符串返回浮点数。
Syntax: float(x)
float() 参数
该方法只接受一个参数,这也是可选的。让我们看看各种类型的参数,方法接受:
A number: Can be an integer or a floating-point number.
A String :
- Must contain numbers of any type.
- Any left or right whitespaces or a new line is ignored by the method.
- Mathematical Operators can be used.
- Can contain NaN, Infinity or inf (any cases)
float() 方法可以根据传递的参数返回的值
- 如果传递了参数,则返回等效的浮点数。
- 如果未传递任何参数,则该方法返回 0.0。
- 如果传递的任何字符串不是小数点数字或与上述任何情况不匹配,则会引发错误。
- 如果传递的数字超出了Python浮点数的范围,则会生成 OverflowError。
在Python示例中浮动
示例 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 \n"))
# 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"))
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"))
Python3
# python code to convert int
# float
number = 90
result = float(number)
print(result)
Python3
# python code to convert string
# to float
string = "90"
result = float(string)
print(result)
Python3
number = "geeks"
try:
print(float(number))
except ValueError as e:
print(e)
输出:
21.89
8.0
23.0
-16.54
-24.45
inf
inf
nan
nan
所有行都正确执行,但最后一行将返回错误:
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"))
输出:
inf
inf
nan
nan
示例 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: Python float() 异常
Python3
number = "geeks"
try:
print(float(number))
except ValueError as e:
print(e)
输出:
could not convert string to float: 'geeks'