I always have to know why, rather than just how, so here I go:
How does this work:
'{0:01.2f}'.format(5.555) #returns '5.55'
'{0:01.1f}'.format(5.555) #returns '5.5'
'{0:1.2f}'.format(5.555) #returns '5.55' again
'{0:1.1f}'.format(5.555) #returns '5.5' again
Why does this not add zero padding by returning ‘05.5’ instead of just ‘5.5’ when I have the extra zero. It just doesn’t seem to work.
Also, why is the string 0:1.1f instead of 0:0.1f, etc. Is it just a convention to use the number 1 before the decimal instead of a zero, or is that the syntax?
Its because the 0 character enables zero-padding, but you have a width of 1 set. Set the width to 2 (like
'{0:02.1f}'and you will see a leading 0.Edit – actually, I’m not sure if 2 will suffice, because I don’t know how it behaves with more digits after the decimal point. So to be safe, make it something like 5 and see what it does then.
Edit 2 – ok, I just tried it. The width corresponds to the TOTAL width, including all digits and the decimal point. So you’ll get this:
Note that the total length of the string is 5 now, with a leading 0 because zero-padding is enabled, and that it truncates to 2 digits after the decimal point because of
.2