本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
float(number=0.0, /)
float(string, /)
-
number/string:要转换为浮点数的字符串或数字。
返回值:
下面是一些使用 float() 函数的示例:
-
示例 1:数字参数
如果不传参数,float() 函数会返回 0.0。
# 整数
int_num = 10
print(float(int_num))
# 输出: 10.0
# 浮点数
float_num_1 = 3.14
print(float(float_num_1))
# 输出: 3.14
float_num_2 = 3.14159265358979323846
print(float(float_num_2))
# 输出: 3.141592653589793
# 不传参数
print(float())
# 输出 0.0
-
示例 2:字符串参数
如果参数是字符串,输入必须符合以下语法中的 floatvalue 生成规则:
1、sign ::= "+" | "-"
2、infinity ::= "Infinity" | "inf"
3、nan ::= "nan"
4、digit ::= <a Unicode decimal digit, i.e. characters in Unicode general category Nd>
5、digitpart ::= digit (["_"] digit)*
6、number ::= [digitpart] "." digitpart | digitpart ["."]
7、exponent ::= ("e" | "E") [sign] digitpart
8、floatnumber ::= number [exponent]
9、absfloatvalue ::= floatnumber | infinity | nan
10、floatvalue ::= [sign] absfloatvalue
具体解释如下:
|
|
|
|
"-" |
|
|
"inf" |
"inf" 、"Inf" 、"INFINITY" 等都是有效的 |
|
|
"nan" 、"NaN" 等都是有效的 |
|
|
0-9 以及一些其他语言中的数字字符 |
|
|
_ 作为分隔符。例如,"123_456" 是有效的 |
|
|
[整数部分] "." [小数部分] ,其中整数部分和小数部分都是可选的,但至少有一个部分必须存在。例如,"123.456" 、".456" 、"123." 都是有效的 |
|
|
"e" 或 "E" 后跟一个可选的符号和一个数字部分。例如,"e3" 、"E-2" 、"e+5" 都是有效的 |
|
|
"123.456e3" 、"123.456E-2" 、"123." 都是有效的 |
|
|
|
|
|
"+123.456" 、"-inf" 、"nan" 都是有效的 |
例如:
# 有效的浮点数字符串
print(float("+123.456")) # 输出:123.456
print(float("-123.456")) # 输出:-123.456
print(float("123.456e3")) # 输出:123456.0
print(float("123.456E-2")) # 输出:1.23456
print(float(".456")) # 输出:0.456
print(float("123.")) # 输出:123.0
print(float("123_456.789")) # 输出:123456.789
print(float("inf")) # 输出:inf
print(float("-Infinity")) # 输出:-inf
print(float("nan")) # 输出:nan
-
示例 3:自定义对象的__float__()和__index__()方法
对于一般的Python对象x,float(x)会调用x.__float__()方法。如果对象没有定义__float__()方法,那么它会调用__index__()方法。
# 自定义对象有 __float__()方法
class MyClass:
def __float__(self):
return 3.14
def __index__(self):
return 42
obj = MyClass()
print(float(obj))
# 输出:3.14
# 自定义对象没有 __float__()方法
class MyOtherClass:
def __index__(self):
return 42
obj2 = MyOtherClass()
print(float(obj2))
# 输出:42.0


本篇文章来源于微信公众号: 码农设计师