round()内置方法使用

round()不是简单的四舍五入的处理方式

下面是引用的官方函数解释:

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

官方函数使用示例:

def round(*args, **kwargs): # real signature unknown
    """
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.
    """
    pass

实际使用程序示例:

 round(1.5)
2
 round(2.5)
2
 round(2.665)
3

  • round()如果只有一个数作为参数,不指定位数的时候:
    返回的是一个整数,而且是最靠近的整数(这点上类似四舍五入)。但是当出现.5的时候,两边的距离都一样,round()取靠近的偶数。
  • 当指定取舍的小数点位数的时候:
    一般情况也是使用四舍五入的规则,但是碰到.5的这样情况,如果要取舍的位数前的小数是奇数,则直接舍弃,如果偶数这向上取舍。
 round(2.635, 2)#小数点后第三位为5,所以看小数点后第2位为3(奇数),所以第三位的5直接舍弃
2.63
 round(2.645, 2)#小数点后第三位为5,所以看小数点后第2位为4(偶数),所以进位
2.65
 round(2.655, 2)
2.65
 round(2.665, 2)
2.67
 round(2.675, 2)
2.67

后续会即是补充

  • 8
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值