Skip to content

Instantly share code, notes, and snippets.

@abhiabhi94
Last active February 9, 2020 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhiabhi94/0aa114241e34537c00f0130b0868b882 to your computer and use it in GitHub Desktop.
Save abhiabhi94/0aa114241e34537c00f0130b0868b882 to your computer and use it in GitHub Desktop.
A django template tag to display numbers in a more readable format e.g: 1K, 123.4K, 111.42M
from django import template
register = template.Library()
@register.filter(name='cool_view', is_safe=False)
def cool_num(val, precision=2):
"""
Convert numbers to a cool format e.g: 1K, 123.4K, 111.42M.
Return
str
e.g: 1K, 123.4K, 111.42M
Params:
val: int
The value of view
precision: int
The precision demanded
"""
try:
int_val = int(val)
except ValueError:
raise template.TemplateSyntaxError(
f'Value must be an integer. {val} is not an integer')
if int_val < 1000:
return str(int_val)
elif int_val < 1_000_000:
return f'{ int_val/1000.0:.{precision}f}'.rstrip('0').rstrip('.') + 'K'
else:
return f'{int_val/1_000_000.0:.{precision}f}'.rstrip('0').rstrip('.') + 'M'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment