首页 > 解决方案 > How to print a given number of decimal places?

问题描述

I want to print my result with a specific number of decimal places inside of a for loop where the value of it is the number of decimal places to be printed.

Below is a sample of the relevant part of the code:

for i in range (-15, -7):    
    print ('Valor do erro:' , 10**i,  'Valor da serie:', count, '------->', '%.16f' % adder(count))

标签: pythonpython-3.x

解决方案


格式说明符可以嵌套:

>>> for i in range(1, 5):
...     print("{:.{}f}".format(1/i, i))
...
1.0
0.50
0.333
0.2500

在这里,1/i转到第一个(外部){...}i第二个(内部){}

但请注意,小数位数不能为负数。为此,您可能只想使用科学记数法

>>> for i in range(-2, 3):
...    print("{:.2e}".format(10**i))
...
1.00e-02
1.00e-01
1.00e+00
1.00e+01
1.00e+02

推荐阅读