详解float函数类型转换

529次阅读
没有评论

详解float函数类型转换

函数描述

float([x]) 函数将数字或数字的字符串表示形式转换为与它等效的有符号浮点数。如果参数x是一个字符串(十进制表示的数字串),数字前面可以添加符号来表示正数,或负数。符号和数字之间不能出现空格,但是符号前面和数字后面允许出现空格。

如果参数 x 是一个整数或是一个浮点数,则返回与它等效的浮点数;如果 x 超出了 float 类型的范围,则引发 OverflowError 错误。

如果参数 x 缺省,则返回 0.0

如果参数 x 是普通的Python对象,float([x]) 返回的是调用 x.__float __() 结果。

兼容性

Python2.x

Python3.x

注意点

1. 这个函数有一个特别的地方,就是使用infinity或inf来表示无穷大的数。比如+inf是正无穷大,-inf是负无穷大。在这里引入了数学上的无穷大概念,那么无穷大乘以0是等于什么呢?在这里是等于nan,即not a number(不是一个数字)

2. 参数x可省略

英文文档

Return a floating point number constructed from a number or string x.
If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded
 in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may 
 also be a string representing a NaN (not-a-number), or a positive or negative infinity.

代码实例

>>> float('+123')
123.0
>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('+inf')
inf
>>> float('nan')
nan
>>> float('+nan')
nan
>>> float('-nan')
nan
>>> float()
0.0

代码实例

class C:
    def __init__(self, score):
        self.score = score
    def __float__(slef):
        return 1.0 
c = C(100)
f = float(c)
print(f)

运行结果

1.0
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-05发表,共计1389字。
新手QQ群:570568346,欢迎进群讨论 Python51学习