Search code examples
pythonstring-formatting

How do I use string formatting to show BOTH leading zeros and precision of 3?


I'm trying to represent a number with leading and trailing zeros so that the total width is 7 including the decimal point. For example, I want to represent "5" as "005.000". It seems that string formatting will let me do one or the other but not both. Here's the output I get in Ipython illustrating my problem:

In [1]: '%.3f'%5
Out[1]: '5.000'

In [2]: '%03.f'%5
Out[2]: '005'

In [3]: '%03.3f'%5
Out[3]: '5.000'

Line 1 and 2 are doing exactly what I would expect. Line 3 just ignores the fact that I want leading zeros. Any ideas? Thanks!


Solution

  • The first number is the total number of digits, including decimal point.

    >>> '%07.3f' % 5
    '005.000'
    

    Important Note: Both decimal points (.) and minus signs (-) are included in the count.