python round函数 竟然把5舍去了

来源:互联网 发布:淘宝代理货源要钱吗 编辑:程序博客网 时间:2024/05/22 13:52
Python 3.6.1 (default, Sep  7 2017, 16:36:03) [GCC 6.3.0 20170406] on linuxType "help", "copyright", "credits" or "license" for more information.>>> round(3.5)4>>> round(3.55, 1)3.5

为什么?据说这跟浮点数的精度有关。我们看到的这个3.55实际上在机器上存储的值是3.54999...999


最终, 我手动写了一个round函数:

def round(n, m=0):    '''round(3.555, 2) => 3.56'''    # python自带的round函数有时会把5舍掉,如round(3.55, 1) => 3.5    if m == 0:        return int(n+0.5)    n = str(int(n*10**m+0.5))    m *= -1    n = '{}.{}'.format(n[:m], n[m:])    return float(n)