Login

Django filter for shrinking [big] numbers

Author:
pedromagnus
Posted:
August 4, 2015
Language:
Python
Version:
1.7
Tags:
filter numbers kilo mega
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

Comments

Please login first before commenting.