Skip to content

Instantly share code, notes, and snippets.

@Lh4cKg
Last active January 23, 2020 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lh4cKg/a86ab37f2070ff3fc9d708d3e8019292 to your computer and use it in GitHub Desktop.
Save Lh4cKg/a86ab37f2070ff3fc9d708d3e8019292 to your computer and use it in GitHub Desktop.
Convert an integer to a string
from django.template import Library
register = Library()
@register.filter(is_safe=True)
def intdivide(value, separator=','):
"""
Convert an integer to a string containing specific separator every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
value = str(value)
divide = len(value) % 3
new_value = str()
for idx, val in enumerate(value):
if idx != 0 and idx == divide:
new_value += separator
elif idx != 0 and (idx - divide) % 3 == 0:
new_value += separator
new_value += val
idx += 1
return new_value
if __name__ == '__main__':
print(intdivide(1, ' '))
print(intdivide(12, ' '))
print(intdivide(123, ' '))
print(intdivide(1234, ' '))
print(intdivide(12345, ' '))
print(intdivide(123456, ' '))
print(intdivide(1234567, ' '))
print(intdivide(12345678, ' '))
print(intdivide(123456789, ' '))
print(intdivide(1234567890, ' '))
print(intdivide(12345678901, ' '))
print(intdivide(123456789012, ' '))
print(intdivide(1234567890123, ' '))
print(intdivide(12345678901234, ' '))
print(intdivide(123456789012345, ' '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment