[Tutor] turning a number into a formated string

Tim Peters tim.peters at gmail.com
Wed Dec 15 21:15:27 CET 2004

[Ertl, John]
> I need to take a number and turn it into a formatted string.
> The final output needs to look like  XXXXYYYY  when the X is the
> integer part padded on the left and  Y is the decimal part padded
> on the right.
> I figured I could split the number at "." and then use zfill or
> something like this  (LEVEL1 = "%04d" % LEVEL1) for the XXXX
> part but I am not sure how to right pad the decimal part of the
> number.
> Example.
> 1 and 1.0  needs to look like 00010000 ( I figured I would have to
> check the length of the list made from the split to see if a decimal
> portion existed)
> 1.1 needs to look like 00011000
> 22.33 needs to look like 00223330

Really?  The input has two digits 3, but the output has three digits
3.  I'll assume you meant 00223300 instead.

> 4444.22 needs to look like 44442200
> Any ideas on the right padding the decimal side using "0"

I expect that a "%09.4f" format does everything you asked for, except
that it contains a period.  So let's try to repair that:

>>> def johnpad(n):
...     return ("%09.4f" % n).replace('.', '')


>>> johnpad(1)
>>> johnpad(1.0)
>>> johnpad(1.1)
>>> johnpad(22.33)
>>> johnpad(4444.22)

More information about the Tutor mailing list