-3

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))
Mikev
  • 2,012
  • 1
  • 15
  • 27
  • where is the function `adder` defined.? What does it do.? Include it in the code so that we can reproduce your issue – Sreeram TP Feb 27 '19 at 10:40

1 Answers1

0

Format-specifiers can be nested:

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

Here, 1/i goes to the first (outer) {...} and i to the second (inner) {}.

Note that the number of decimal places can not be negative, though. For this, you might just want to use scientific notation instead.

>>> 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
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • This results in an error: "ValueError: Format specifier missing precision" – Pedro Unas Feb 27 '19 at 10:59
  • @PedroUnas Not for me. What version of Python are you using? Also, `i` should probably not ne negative, as in your loop. What precision would you expect then? – tobias_k Feb 27 '19 at 11:49