MrHize
MrHize

Reputation: 220

How to format numbers from 1000 to 1k in django

I am working on a project in Django, i have created a template_tags.py files in my project. How do i format numbers from 1000 to 1k, 2000 to 2k, 1000000 to 1m and so on. But i am having an issue with my code, instead of getting 1000 to 1k, i got 1000 to 1.0k. What am i missing in my code?

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.0, 'k')
    return value

Upvotes: 1

Views: 2682

Answers (2)

Jorge Luis
Jorge Luis

Reputation: 957

https://docs.djangoproject.com/en/3.0/ref/contrib/humanize/

You can also check for this template filters in the official documentation of Django. This one makes what you want and other things

Upvotes: 0

Ben
Ben

Reputation: 2547

You appear to be formatting with 1 decimal. If you don't want the decimal or numbers after it, change the 1 to a 0. You also need to have value_int >= <number> otherwise 1000000 and 1000 won't be converted:

[...]
    if value_int >= 1000000:
        value = "%.0f%s" % (value_int/1000000.00, 'M')
    else:
        if value_int >= 1000:
            value = "%.0f%s" % (value_int/1000.0, 'k')

Upvotes: 2

Related Questions