• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python函数 – float函数类型转换详解

python 搞java代码 3年前 (2022-05-21) 15次浏览 已收录 0个评论
文章目录[隐藏]

函数描述

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
')
-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

www#gaodaima.com来源gao($daima.com搞@代@#码(网搞代码

代码实例2

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

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python函数 – float函数类型转换详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址