python的float函数_详解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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值