• Python内置函数(55)——round


    英文文档:

    round(number[, ndigits])
    Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it returns the nearest integer to its input. Delegates to number.__round__(ndigits).
    For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). The return value is an integer if called with one argument, otherwise of the same type as number.
    Note:
    The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.  
    说明:

    1. round函数用于对浮点数进行四舍五入求值,具体保留几位小数,以传入的ndigits参数来控制。

    >>> round(1.1314926,1)
    1.1
    >>> round(1.1314926,5)
    1.13149
    2. ndigits参数为可选参数,当不传入时,即以默认保留0位小数进行取整,返回的是整数。

    >>> round(1.1314926)
    1
    3. ndigits参数传入0时,虽然与不传入ndigits参数一样保留0位小数进行四舍五入,但是返回的值是浮点型。

    >>> round(1.1314926,0)
    1.0
    4. ndigits参数小于0时,对整数部分进行四舍五入,ndigits参数控制了对浮点数的整数部分的后几位进行四舍五入,小数部分全部清0,返回类型是浮点数。如果传入的浮点数的整数部分位数小于ndigits参数绝对值,则返回0.0.

    >>> round(11314.926,-1)
    11310.0
    >>> round(11314.926,-3)
    11000.0
    >>> round(11314.926,-4)
    10000.0
    >>> round(11314.926,-5)
    0.0
    5. round四舍五入时是遵循靠近0原则,所以-0.5和0.5进行0位四舍五入,返回的都是0.

    >>> round(0.5)
    0
    >>> round(-0.5)
    0
    6. 对于浮点数求四舍五入有一个陷阱,有些四舍五入结果不像预期那样,比如round(2.675, 2) 的结果是2.67 而不是预期的 2.68,这不是bug,而是浮点数在存储的时候因为位数有限,实际存储的值和显示的值有一定误差。

    >>> round(2.675, 2)
    2.67
    7. 对整数也能进行round操作,返回值也是整形。

    >>> round(134567)
    134567
    >>> round(134567,0)
    134567
    >>> round(134567,1)
    134567
    >>> round(134567,2)
    134567
    >>> round(134567,-2)
    134600
    >>> round(134567,-6)
    0

  • 相关阅读:
    如何排查Java内存泄漏?
    自动化测试执行过程和报告内容分析
    计算机毕业设计ssm全美旅行社网站3ircv系统+程序+源码+lw+远程部署
    软件开发项目文档系列之三如何撰写项目招标文件
    【Javascript】DOM文档
    MyBatis 学习(七)之 缓存
    EMA算法
    第九章:最新版零基础学习 PYTHON 教程—Python 元组(第五节 -清除元组的5种方式方法)
    如何成为高级网络工程师?
    日常练习-4
  • 原文地址:https://blog.csdn.net/s13596191285/article/details/128214821