• 技术文章 >Python技术 >Python基础教程

    详解float函数类型转换

    silencementsilencement2019-07-18 09:27:11原创6207

    函数描述

    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可省略

    英文文档

    1

    2

    3

    4

    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.

    代码实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

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

    代码实例

    1

    2

    3

    4

    5

    6

    7

    8

    class C:

        def __init__(self, score):

            self.score = score

        def __float__(slef):

            return 1.0

    c = C(100)

    f = float(c)

    print(f)

    运行结果

    1

    1.0

    专题推荐:float
    上一篇:Python中format函数字符串格式化入门 下一篇:Python小白福利之enumerate函数

    相关文章推荐

    • Python正则表达式findall函数详解

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网