Created
July 11, 2012 15:55
-
-
Save thanos/3091327 to your computer and use it in GitHub Desktop.
Django quantity format template tag/filter
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
| @register.filter(name='quantityformat') | |
| def quantityformat(bytes): | |
| """ | |
| Formats the value like a 'human-readable' file size (i.e. 13K, 4.1M, | |
| 102, etc). | |
| """ | |
| try: | |
| bytes = float(bytes) | |
| except (TypeError,ValueError,UnicodeDecodeError): | |
| return ungettext("%(size)d", "%(size)d", 0) % {'size': 0} | |
| filesize_number_format = lambda value: formats.number_format(round(value, 1), 1) | |
| if bytes < 1024: | |
| return ungettext("%(size)d", "%(size)d", bytes) % {'size': bytes} | |
| if bytes < 1024 * 1024: | |
| return ugettext("%sK") % filesize_number_format(bytes / 1024) | |
| if bytes < 1024 * 1024 * 1024: | |
| return ugettext("%sM") % filesize_number_format(bytes / (1024 * 1024)) | |
| if bytes < 1024 * 1024 * 1024 * 1024: | |
| return ugettext("%sG") % filesize_number_format(bytes / (1024 * 1024 * 1024)) | |
| if bytes < 1024 * 1024 * 1024 * 1024 * 1024: | |
| return ugettext("%sT") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024)) | |
| return ugettext("%sP") % filesize_number_format(bytes / (1024 * 1024 * 1024 * 1024 * 1024)) | |
| quantityformat.is_safe = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment