def new_round(_float, _len): ''' 浮点数小数点四舍五入的实现,解决原有round的遇5不舍弃的bug ''' if str(_float)[-1] == '5': return(round(float(str(_float)[:-1]+'6'), _len)) else: return(round(_float, _len))
-----------------------------------------------------------------------------------------------------------------------------------------------
round函数的bug
round(2.675, 2) 2.67
为什么会这样呢?原因是:round()函数只有一个参数,不指定位数的时候,返回一个整数,而且是最靠近的整数,类似于四舍五入,当指定取舍的小数点位数的时候,一般情况也是使用四舍五入的规则,但是碰到.5的情况时,如果要取舍的位数前的小数是奇数,则直接舍弃,如果是偶数则向上取舍。