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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 months ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 5 months ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 1 week ago

Comments

Please login first before commenting.