温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

float函数类型如何转换

发布时间:2020-09-24 11:55:21 来源:亿速云 阅读:312 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关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

上述就是小编为大家分享的float函数类型如何转换了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI