Formatting numbers

Andrew Henshaw andrew_dot_henshaw_at_earthling_dot_net
Wed May 2 01:19:35 EDT 2001


"Siggy Brentrup" <bsb at winnegan.de> wrote in message
news:mailman.988761783.7383.python-list at python.org...
> "Daniel Klein" <DanielK at jBASE.com> writes:
>
> > This is almost embarrasing to have to ask this but I can't seem to find
this
> > information.
> >
> > Given an integer, 12345, how to format this to 123.45 ?
>
> def fixed(i, places=2):
>     """12345 -> 123.45"""
>     if i >= 0:
>         s = '%0*d' % (places+1,i)
>     else:
>         s = '%0*d' % (places+2,i)
>     return s[:-places]+'.'+s[-places:]
>
> >>> print fixed(12345), fixed(12345,6), fixed(-1)
> 123.45 0.012345 -0.01

I like this the best so far.  Perhaps we won't offend anyone with:

def fixed(i, places=2):
    """12345 -> 123.45"""
    s = '%0*d' % (places + 1 + (i<0), i)
    return s[:-places] + '.' + s[-places:]

Andy Henshaw







More information about the Python-list mailing list