Login

Pad integers with leading zeros (template filter)

Author:
jcroft
Posted:
January 11, 2008
Language:
Python
Version:
.96
Tags:
template filter
Score:
-2 (after 2 ratings)

Disclaimer: I'm not the world's greatest programmer, so there may be better ways to do this, but it works for me (feel free to offer your improvements, though!).

Basically, this will pad an integer with leading zeros and return a string representation. User it like this:

{% forloop.counter|leading_zeros:"5" %}

...where "5" is the number of desired digits. In this case, if it was the 12th time through the forloop, the filter would return "00012".

Why do this? Either for alignment, such as in tables, or for aesthetics -- for an example, see Shaun Inman's comment section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@register.filter
def leading_zeros(value, desired_digits):
  """
  Given an integer, returns a string representation, padded with [desired_digits] zeros.
  """
  num_zeros = int(desired_digits) - len(str(value))
  padded_value = []
  while num_zeros >= 1:
    padded_value.append("0") 
    num_zeros = num_zeros - 1
  padded_value.append(str(value))
  return "".join(padded_value)

More like this

Comments

kioopi (on January 11, 2008):
<p>hey, doesn't</p> <pre>def leading_zeros(value, desired_digits): return str(value).zfill(desired_digits) </pre> <p>do the same thing?</p>

#

jcroft (on January 11, 2008):
<p>Probably. And I've also been informed that you can use the string formatting built-in template tag to accomplish this:</p> <pre>{{ var_containing_number|stringformat:"05d" }} </pre> <p>So, yeah -- good idea, but maybe not the best way to do it. I sort of suspected there was probably a better way. :)</p>

#

laffuste (on March 5, 2013):
<p>Or, without template tags:</p> <p>padded_value = "%05d" % value</p> <p>(for a 5 digit padded number)</p>

#

jnns (on February 28, 2014):
<p>Well, thanks anyway jcroft! I was looking for zero-padding for Django templates and now I know about at least two simple solutions.</p>

#

Please login first before commenting.