python保存两位小数的几种方法,python2保留小数

文章目录

  • 一、保留两位小数 且 做四舍五入处理
  • 1、使用字符串格式化
  • 2、使用python内置的round() 函数
  • 3、使用python内置的decimal模块
  • 二、保留两位小数 且 不做四舍五入处理
  • 1、使用序列中的切片
  • 2、使用re正则匹配模块
  • 三、python2保留小数
  • 一、保留两位小数 且 做四舍五入处理

    1、使用字符串格式化

    
    >>> x = 3.1415926
    >>> print("%.2f" % x)
    3.14
    >>>
    

    2、使用python内置的round() 函数

    >>> x = 3.1415926
    >>> round(x, 2)
    3.14
    >>>
    

    round()函数的官方定义:

    def round(number, ndigits=None): # real signature unknown; restored from __doc__
        """
        round(number[, ndigits]) -> number
        
        Round a number to a given precision in decimal digits (default 0 digits).
        This returns an int when called with one argument, otherwise the
        same type as the number. ndigits may be negative.
        """
        return 0
    

    3、使用python内置的decimal模块

    decimal 英 /'desɪm(ə)l/ 小数的
    quantize 英 /'kwɒntaɪz/ 量化

    >>> from decimal import Decimal
    >>> x = 3.1415926
    >>> Decimal(x).quantize(Decimal("0.00"))
    Decimal('3.14')
    >>> a = Decimal(x).quantize(Decimal("0.00"))
    >>> print(a)
    3.14
    >>> type(a)
    <class 'decimal.Decimal'>
    >>> b = str(a)
    >>> b
    '3.14'
    

    二、保留两位小数 且 不做四舍五入处理

    1、使用序列中的切片

    >>> x = 3.1415926
    >>> str(x).split(".")[0] + "." + str(x).split(".")[1][:2]
    '3.14'
    

    2、使用re正则匹配模块

    >>> import re
    >>> x = 3.1415926
    >>> re.findall(r"\d{1,}?\.\d{2}", str(a))
    ['3.14']
    

    三、python2保留小数

    1、python2中除法,默认是取,也就是在做除法的时候你是无法获取小数部分的!

    如下:

    2、解决方法,就是在脚本文件中开头导入未来版本功能,如下:

    from __future__ import division
    import os
    
    print(2/3)
    

    注意:

    from __future__ import division一定要在其他模块之前导入,否则报错!




    ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

    作者:点亮~黑夜

    物联沃分享整理
    物联沃-IOTWORD物联网 » python保存两位小数的几种方法,python2保留小数

    发表回复