Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round, align and print list of floats with format()

I need to write several floats to file for which I am using the format() method. What I want is to round the floats to a given number of decimal places and write them aligned at the same time.

Here's a MWE:

a = 546.35642
b = 6785.35416
c = 12.5235
d = 13.643241

line = [str('{:.2f}'.format(a)),
    str('{:.4f}'.format(b)),
    str('{:.5f}'.format(c)),
    str('{:.3f}'.format(d))]

with open('format_test.dat', "a") as f_out:
    f_out.write('''{:>10} {:>15} {:>16} {:>15}'''.format(*line))
    f_out.write('\n')

This gets the job done but it seems awfully convoluted to me. Is there a better way to do this using format()?

like image 862
Gabriel Avatar asked Sep 30 '22 21:09

Gabriel


1 Answers

You can just add the .#f in the format with the alignment.

with open('format_test.dat', "a") as f_out:
    f_out.write('''{:>10.2f} {:>15.4f} {:>16.5f} {:>15.3f}'''.format(a, b, c, d))
    f_out.write('\n')
like image 169
SethMMorton Avatar answered Oct 12 '22 23:10

SethMMorton