0

I've been working on this assignment for one of my class and I can't figure out how to round to 2 decimal even if it's .00

I'm printing a table and it just look's weird here's my result :

             1           10000.0             600.0           10600.0
             2           10600.0             636.0           11236.0
             3           11236.0            674.16          11910.16
             4          11910.16            714.61          12624.77
             5          12624.77            757.49          13382.26
             6          13382.26            802.94          14185.19
             7          14185.19            851.11           15036.3
             8           15036.3            902.18          15938.48
             9          15938.48            956.31          16894.79
            10          16894.79           1013.69          17908.48

I print a list of item that I round to 1 for [0] and to 2 for the rest (Sorry some of the var are in french XD)

for n in i_liste_l:
    if n == i_liste_l[0]:
        n = int(round(n,0))
        i_liste_l[0] = n
    else:
        index_i = int(i_liste_l.index(n))
        i_liste_l[index_i] = float(round(n,2))
i = i+1

print('{:>{width}}{:>{width}}{:>{width}}{:>{width}}'.format(*i_liste_l,width = indent))
SKTLZ
  • 163
  • 1
  • 4
  • 12

3 Answers3

4

For the purposes of the question I'm-a filling in some of the values:

print('{:>{width}}{:>{width}}{:>{width}}{:>{width}}'.format(1.2, 1, 4.32, 65.3, width=7))
#>>>     1.2      1   4.32   65.3

You want the .Nf formatter:

print('{:>{width}.2f}{:>{width}.2f}{:>{width}.2f}{:>{width}.2f}'.format(1.2, 1, 4.32, 65.3, width=7))
#>>>    1.20   1.00   4.32  65.30
Veedrac
  • 58,273
  • 15
  • 112
  • 169
0

You can use:

print('%5.2f' % 1.0)

to print

 1.00 # a space in front, 4 characters for the numbers, total 5
justhalf
  • 8,960
  • 3
  • 47
  • 74
0

You need to use "%.2f"

Example -

>>> x = 10.0/2
>>> print x
5.0
>>> print "%.2f" % x
5.00
>>> x = 5.0/2
>>> print "%.2f" % x
2.50
theharshest
  • 7,767
  • 11
  • 41
  • 51
  • The .format() syntax is considered to be the way to go for string formatting now as its more precise and in depth. Also, how is this different to the answer by @justhalf which was answered earlier? –  Sep 26 '13 at 07:02