美文网首页
4-1对数值取整、精确计算和格式化输出

4-1对数值取整、精确计算和格式化输出

作者: cuzz_ | 来源:发表于2018-03-03 22:54 被阅读0次

    对数值取整

    当我们想要将一个浮点数取整到固定的小数位
    对于简单的取整操作,可以使用round(value, ndigits)函数,采用四舍五入取值

    >>> round(1.23, 1)
    1.2
    >>> round(1.25, 1)
    1.3
    

    round()中的参数ndigits可以是负数,这种情况下会相应的取整到十位、百位、千位

    >>> a = 123456
    >>> round(a, -1)
    123460
    >>> round(a, -2)
    

    精确度的小数计算

    我们需要对小数进行计算时,不希望因为浮点数天生的误差而带来的影响

    >>> a = 4.2
    >>> b = 2.1
    >>> a + b
    6.300000000000001
    >>> (a + b) == 6.3
    False
    

    如果希望得到更高的精度(牺牲一些性能),可以使用decimal模块

    >>> from decimal import Decimal
    >>> a = Decimal("4.2")
    >>> b = Decimal("2.1")
    >>> a + b
    Decimal('6.3')
    >>> print(a + b)
    6.3
    >>> (a + b) == Decimal("6.3")
    True
    

    对数值做格式化输出

    对一个单独的数值做格式化输出,使用内建的format()函数

    >>> x = 1234.56789
    # 0.2f 其中0表示默认位数,2表示小数位数,f 表示数据类型
    >>> format(x, "0.2f")
    '1234.57'
    >>> format(x, "10.2f")
    '   1234.57'
    >>> format(x, ">10.2f")
    '   1234.57'
    >>> format(x, "<10.2f")
    '1234.57   '
    >>> format(x, "^10.2f")
    ' 1234.57  '
    

    相关文章

      网友评论

          本文标题:4-1对数值取整、精确计算和格式化输出

          本文链接:https://www.haomeiwen.com/subject/byyxfftx.html