Pad integers with leading zeros (template filter)

 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

  1. Avoid widows using a template filter by jcroft 6 years, 2 months ago
  2. table with n items per row using custom modulo tag by elgreengeeto 4 years, 5 months ago
  3. RPN template math by durka 4 years, 6 months ago
  4. Template range loop by nfg 3 years, 3 months ago
  5. Find all links in a value and display them separatley by jcroft 6 years, 2 months ago

Comments

kioopi (on January 11, 2008):

hey, doesn't

def leading_zeros(value, desired_digits):
    return str(value).zfill(desired_digits)

do the same thing?

#

jcroft (on January 11, 2008):

Probably. And I've also been informed that you can use the string formatting built-in template tag to accomplish this:

{{ var_containing_number|stringformat:"05d" }}

So, yeah -- good idea, but maybe not the best way to do it. I sort of suspected there was probably a better way. :)

#

laffuste (on March 5, 2013):

Or, without template tags:

padded_value = "%05d" % value

(for a 5 digit padded number)

#

(Forgotten your password?)