Search code examples
pythonfloating-pointformattingtabular

Formatting float in python also before the decimal separator


I am formatting floats as follows:

logFile.write("Loadcase: %6i %2i %4i %2.2f %2.2f %4f + %4f -> " %(i, freq, amp, cutoff, end_time, penalty_inc, stab_inc))

and the result is like:

Loadcase:   5001  1   50 19.00 20.00 0.000000 + 0.000000 -> 0.495386 (ok)
Loadcase:   5002  2   50 9.50 10.00 0.000000 + 0.000000 -> 0.255045 (ok)
Loadcase:   5003  3   50 6.33 6.67 0.000000 + 0.000000 -> 0.151464 (ok)
Loadcase:   5005  5   50 3.80 4.00 0.000000 + 0.000000 -> 0.116979 (ok)
Loadcase:   5010 10   50 1.90 2.00 0.000000 + 0.000000 -> 0.081181 (ok)

I simply want the floats to be right aligned and some spaces inserted where necessary. I really basically want the table to be nicely aligned. My guess of writing %2.2f seems to be ignored.

I cannot use numpy for technical reasons.


Solution

  • You're misunderstanding what %2.2f means. It means "give the float 2 columns total, and display 2 positions after the radix point". Perhaps you want %5.2f instead.