如何在python3中精确打印大量小数对象?

时间:2019-12-16 17:22:50

标签: python python-3.x

我想在python3.6中打印大量的小数对象

import decimal

a = decimal.Decimal('0.0')

for idx in range(10):
    a += decimal.Decimal('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.11111111111111111111')
    print(a)

我想要的执行结果如下。

1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.11111111111111111111
2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222.22222222222222222222
3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333.33333333333333333333
4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444.44444444444444444444
5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555.55555555555555555555
6666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666.66666666666666666666
7777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777.77777777777777777777
8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888.88888888888888888888
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999.99999999999999999999
11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.11111111111111111110

但是实际执行结果如下。

1.111111111111111111111111111E+99
2.222222222222222222222222222E+99
3.333333333333333333333333333E+99
4.444444444444444444444444444E+99
5.555555555555555555555555555E+99
6.666666666666666666666666666E+99
7.777777777777777777777777777E+99
8.888888888888888888888888888E+99
9.999999999999999999999999999E+99
1.111111111111111111111111111E+100

如何获得想要的结果?

1 个答案:

答案 0 :(得分:2)

您可以使用字符串格式,但在此之前必须设置精度(十进制的默认值为28位)

GET /company/{id}/location/{locId} - Return custom location settings OR default
PUT /company/{id}/location/{locId} - Update custom location for location

打印:

import decimal

a = decimal.Decimal('0.0')

with decimal.localcontext() as ctx:
    ctx.prec = 120

    for idx in range(10):
        a += decimal.Decimal('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.11111111111111111111')
        print('{:.20f}'.format(a))