Python浮点数数据精度控制

代码

import decimal
from decimal import Decimal, getcontext

if __name__ == '__main__':
    decimal.getcontext().prec = 2
    for i in range(4):
        x = i / 3
        print()
        print(x)
        print(decimal.Decimal(x))
        print("%0.2f"%x)
        print(eval("'%0." + str(a) + "f'" + "%x"))
        print(float("%0.2f"%x))

返回

0.0
0
0.00
0.00
0.0

0.3333333333333333
0.333333333333333314829616256247390992939472198486328125
0.33
0.33
0.33

0.6666666666666666
0.66666666666666662965923251249478198587894439697265625
0.67
0.67
0.67

1.0
1
1.00
1.00
1.0
原文地址:https://www.cnblogs.com/bitquant/p/11679272.html