Finding field widths of floats for neat printing

Scott David Daniels Scott.Daniels at Acm.Org
Fri Apr 4 06:22:23 CEST 2003


Andrew Gregory wrote:

 > I want to write lists of floating point numbers to text files in neat
 > columns with decimal points aligned, right-hand edges straight (rather
 > than ragged), and without unnecessary trailing zeros, e.g.
 > 1.1    -34.67     0.006
 > 2.0     -1.05     0.010
 > etc.
 >
 > In order to do this I need to loop through the lists of numbers for
 > each column to find the field sizes m and n need to achieve this. I
 > can then produce a format specifier string (fss) for each column,
 > e.g. fss = "%" + "%i.%if" % (m,n)
 >
 > Given a number, -34.67 for example is there a SMART Python way of
 > determining the field sizes? Obviously I need to work at less than the
 > precision of the machine, and ignore the fact that -34.67 might be
 > represented as
 > -34.6699999999999
 >

How about something involving:
     import os.path

     def reverse(str):
         l = list(str)
         l.reverse()
         return ''.join(l)

     numbers = [1.1, 11.77, 23, 107.333]

     final = 12 - len(os.path.commonprefix(['0'*12]+
              [reverse('%.12f' % x)
               for x in numbers])

-Scott David Daniels
Scott.Daniels at Acm.Org





More information about the Python-list mailing list