Skip to content

Instantly share code, notes, and snippets.

@dnmellen
Last active July 26, 2022 10:43
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dnmellen/bfc1b3005999aaff3ed4 to your computer and use it in GitHub Desktop.
Save dnmellen/bfc1b3005999aaff3ed4 to your computer and use it in GitHub Desktop.
Adds @danielafcarey fix
from django import template
register = template.Library()
@register.filter
def cool_number(value, num_decimals=2):
"""
Django template filter to convert regular numbers to a
cool format (ie: 2K, 434.4K, 33M...)
:param value: number
:param num_decimals: Number of decimal digits
"""
int_value = int(value)
formatted_number = '{{:.{}f}}'.format(num_decimals)
if int_value < 1000:
return str(int_value)
elif int_value < 1000000:
return formatted_number.format(int_value/1000.0).rstrip('0').rstrip('.') + 'K'
else:
return formatted_number.format(int_value/1000000.0).rstrip('0').rstrip('.') + 'M'
@cwazuidema
Copy link

Thank you!

@suiris31
Copy link

Perfect thank you

@teury
Copy link

teury commented Jul 2, 2019

Thank

@danielafcarey
Copy link

This is great - thank you! One small note is that it doesn't work for numbers like 40000 because the rstrip('0.') strips all the combinations of the passed in char string so it would result in 40.0 being stripped down to 4 and output 4k when it should be 40k

A workaround I found was to replace rstrip('0.') with rstrip('0').rstrip('.') which will remove all trailing zeros and then any trailing decimals.

@IamMiracleAlex
Copy link

@dnmellen Thank you for this awesome piece!
@danielafcarey Thank you for the correction, it was really helpful!

@dantechplc
Copy link

Please how do I use it in my template? Thanks

@dnmellen
Copy link
Author

@danielafcarey Thanks for your correction!

@dantechplc Checkout Django's docs about custom filters (https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/). You need to add this file inside templatetags folder within your django app directory as it says in the docs. After that you can load that custom filter in your template and use it:

{% load numbers %}

...

{{ yourvar|cool_number }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment