Login

Django filter for shrinking [big] numbers

Author:
pedromagnus
Posted:
August 4, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

Simple filter that shrinks [big] numbers sufixing "M" for numbers bigger than million, or "K" for numbers bigger than thousand. It does a division over the number before converting to string so rounding is properly done.

Examples:

{{ 123456|shrink_num }} >> 123.6K

{{ 1234567|shrink_num }} >> 1.2M

 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
from django import template


register = template.Library()


@register.filter
def shrink_num(value):
    """
    Shrinks number rounding
    123456  > 123,5K
    123579  > 123,6K
    1234567 > 1,2M
    """
    value = str(value)

    if value.isdigit():
        value_int = int(value)

        if value_int > 1000000:
            value = "%.1f%s" % (value_int/1000000.00, 'M')
        else:
            if value_int > 1000:
                value = "%.1f%s" % (value_int/1000.00, 'K')
    return value

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.