Last active
January 23, 2020 11:17
-
-
Save Lh4cKg/a86ab37f2070ff3fc9d708d3e8019292 to your computer and use it in GitHub Desktop.
Convert an integer to a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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