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

Question:

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!

Asked By: cat

||

Answers:

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.

Answered By: nosklo

[Edit: Gah, beaten again]

'%07.3F'%5

The first number is the total field width.

Answered By: babbitt

This took me a second to figure out how to do @nosklo’s way but with the .format() and being nested.

Since I could not find an example anywhere else atm I am sharing here.

Example using "{}".format(a)

Python 2

>>> a = 5
>>> print "{}".format('%07.3F' % a)
005.000
>>> print("{}".format('%07.3F' % a))
005.000

Python 3

More python3 way, created from docs, but Both work as intended.

Pay attention to the % vs the : and the placement of the format is different in python3.

>>> a = 5
>>> print("{:07.3F}".format(a))
005.000
>>> a = 5
>>> print("Your Number is formatted: {:07.3F}".format(a))
Your Number is formatted: 005.000

Example using "{}".format(a) Nested

Then expanding that to fit my code, that was nested .format()‘s:

print("{}: TimeElapsed: {} Seconds, Clicks: {} x {} "
      "= {} clicks.".format(_now(),
                            "{:07.3F}".format((end -
                                               start).total_seconds()),
                            clicks, _ + 1, ((_ + 1) * clicks),
                            )
      )

Which formats everything the way I wanted.

Result

20180912_234006: TimeElapsed: 002.475 Seconds, Clicks: 25 + 50 = 75 clicks.

Important Things To Note:

  • @babbitt: The first number is the total field width.

  • @meawoppl: This also counts the minus sign!…

Answered By: JayRizzo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.