-
-
Save felix13/6d8cc9465da9831625e62e669598ba0d to your computer and use it in GitHub Desktop.
Simple template filter for django to convert numbers to cool format (2.3K, 4M, etc..)
This file contains hidden or 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 | |
| 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.') + 'K' | |
| else: | |
| return formatted_number.format(int_value/1000000.0).rstrip('0.') + 'M' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment