0

I want to format float values in my django template like this:

125000 => 125k

125,000,000 => 125M

Do I have to use any custom template tag for this or django already has one?

Any idea?

Niladry Kar
  • 1,163
  • 4
  • 20
  • 50
  • Look at [django.contrib.humanize](https://docs.djangoproject.com/en/2.2/ref/contrib/humanize/), probably not exactly what you need, but that gives you an idea how to write your own filter. – dirkgroten Jun 03 '19 at 10:28

2 Answers2

1

You can use that by the below filter template tag:

@register.filter
def format_number(num):
    num = int(num)
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

print(format_number(32413423)) # 32.41M

It is going to support to P

I've created the code using this link: formatting long numbers as strings in python

Alireza HI
  • 1,873
  • 1
  • 12
  • 20
0

This is the list of built-in template tags and filters so if it's not there, you have to build your own.

You'll find something similar to what you need in django.contrib.humanize, use this as the basis to build your own filter.

dirkgroten
  • 20,112
  • 2
  • 29
  • 42