Last active
February 9, 2020 10:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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