- Author:
- agusmakmun
- Posted:
- September 11, 2019
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
Templatetags function to convert the number into numberize method. It usefull to numberize the visitors, users, or other cases.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | from django import template
register = template.Library()
@register.filter
def numberize(number):
"""
return convert number to string, an example:
- 1000 to 1k
- 1000000 to 1m, etc.
:param `number` is number to convert.
usage:
{{ post.get_visitors.count|numberize }}
"""
scales = {
1000: 'k',
1000000: 'm',
1000000000: 'b',
1000000000000: 't',
1000000000000000: 'quad',
1000000000000000000: 'quin',
1000000000000000000000: 'sexti',
1000000000000000000000000: 'septi',
1000000000000000000000000000: 'octi',
1000000000000000000000000000000: 'noni',
1000000000000000000000000000000000: 'deci',
1000000000000000000000000000000000000: 'undeci',
1000000000000000000000000000000000000000: 'duodeci',
1000000000000000000000000000000000000000000: 'trede',
1000000000000000000000000000000000000000000000: 'quattu',
1000000000000000000000000000000000000000000000000: 'quindeci',
1000000000000000000000000000000000000000000000000000: 'sexdeci',
1000000000000000000000000000000000000000000000000000000: 'septend',
1000000000000000000000000000000000000000000000000000000000: 'octodeci',
1000000000000000000000000000000000000000000000000000000000000: 'novemdeci',
1000000000000000000000000000000000000000000000000000000000000000: 'vigintillion',
1000000000000000000000000000000000000000000000000000000000000000000: 'infinity'
}
try:
number = int(number)
except ValueError:
return number
for digit, name in scales.items():
minimum = '9' * len(str(digit)[1:])
maximum = minimum + '999'
if number > max(scales):
return "{0:.1f} ".format(number / max(scales)) + name
elif number > int(minimum) and number <= int(maximum):
return "{0:.1f} ".format(number / digit) + name
return number
"""
print(numberize(10)) # 10
print(numberize(2222)) # 2.2 k
print(numberize(3919393)) # 3.9 m
print(numberize(2147483647)) # 2.1 b
print(numberize(2347483648887)) # 2.3 t
print(numberize(9223372036854775807)) # 9.2 quin
"""
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.