Niladry Kar
Niladry Kar

Reputation: 1203

How to format float values in django template?

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?

Upvotes: 0

Views: 1695

Answers (2)

Alireza HI
Alireza HI

Reputation: 1933

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

Upvotes: 1

dirkgroten
dirkgroten

Reputation: 20702

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.

Upvotes: 0

Related Questions