Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number containing a decimal point with leading zeroes

I want to format a number with a decimal point in it with leading zeros.

This

>>> '3.3'.zfill(5)
003.3

considers all the digits and even the decimal point. Is there a function in python that considers only the whole part?

I only need to format simple numbers with no more than five decimal places. Also, using %5f seems to consider trailing instead of leading zeros.

like image 659
3eee3 Avatar asked Sep 13 '11 20:09

3eee3


People also ask

How do I format leading zeros in Excel?

Select the cell or range of cells that you want to format. Press Ctrl+1 to load the Format Cells dialog. Select the Number tab, then in the Category list, click Custom and then, in the Type box, type the number format, such as 000-00-0000 for a social security number code, or 00000 for a five-digit postal code.

Do leading zeros count if there is a decimal?

3. Leading zeros are NOT significant. They're nothing more than "place holders." The number 0.54 has only TWO significant figures. 0.0032 also has TWO significant figures.


2 Answers

I like the new style of formatting.

loop = 2
pause = 2
print 'Begin Loop {0}, {1:06.2f} Seconds Pause'.format(loop, pause)
>>>Begin Loop 2, 0002.1 Seconds Pause

In {1:06.2f}:

  • 1 is the place holder for variable pause
  • 0 indicates to pad with leading zeros
  • 6 total number of characters including the decimal point
  • 2 the precision
  • f converts integers to floats
like image 140
Bill Kidd Avatar answered Sep 27 '22 20:09

Bill Kidd


Is that what you look for?

>>> "%07.1f" % 2.11
'00002.1'

So according to your comment, I can come up with this one (although not as elegant anymore):

>>> fmt = lambda x : "%04d" % x + str(x%1)[1:]
>>> fmt(3.1)
0003.1
>>> fmt(3.158)
0003.158
like image 38
rumpel Avatar answered Sep 27 '22 20:09

rumpel