python四舍五入精度问题

python四舍五入中的坑

1
2
3
4
5
6
7
8
9
10
print(round(1.113, 2))
print(round(1.115, 2))
print(round(1.125, 2))
print(round(1.375, 2))

out:
1.11
1.11
1.12
1.38
  • round四舍五入时遇到进位为5的情况,就会导致不准确的情况,归根结底是计算机存储浮点数的问题

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    from decimal import Decimal
    print(Decimal(1.113))
    print(Decimal(1.115))
    print(Decimal(1.125))
    print(Decimal(1.375))

    out:
    1.112999999999999989341858963598497211933135986328125
    1.1149999999999999911182158029987476766109466552734375
    1.125
    1.375
  • 解决方法:加上一个不影响四舍五入的小数

    python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    print(round(1.113+0.00000001, 2))
    print(round(1.115+0.00000001, 2))
    print(round(1.125+0.00000001, 2))
    print(round(1.375+0.00000001, 2))

    out:
    1.11
    1.12
    1.13
    1.38