Ticket #6391: filesizeformat.diff

File filesizeformat.diff, 1.6 KB (added by Marc Fargas, 16 years ago)

initial patch against latest trunk

  • django/contrib/humanize/templatetags/humanize.py

    diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py
    index 4aa5a32..efb1638 100644
    a b from django import template  
    44from django.template import defaultfilters
    55from django.conf import settings
    66from datetime import date, timedelta
     7import math
    78import re
    89
    910register = template.Library()
    def naturalday(value, arg=None):  
    9899        return _(u'yesterday')
    99100    return defaultfilters.date(value, arg)
    100101register.filter(naturalday)
     102
     103def filesizeformat(bytes, precision=2):
     104    """ Returns a human readable string of a byte count. """
     105    bytes = int(bytes)
     106    if bytes is 0:
     107        return u'0%s' % _(u'bytes')
     108    log = math.floor(math.log(bytes, 1024))
     109    return "%.*f%s" % (
     110        precision,
     111        bytes / math.pow(1024, log),
     112        [_(u'bytes'), u'kb', u'mb', u'gb', u'tb', u'pb', u'eb', u'zb', u'yb'][int(log)]
     113        )
     114register.filter(filesizeformat)
     115
  • docs/add_ons.txt

    diff --git a/docs/add_ons.txt b/docs/add_ons.txt
    index 029e314..b389649 100644
    a b Values up to 1000000000000000 (one quadrillion) are supported.  
    141141
    142142You can pass in either an integer or a string representation of an integer.
    143143
     144filesizeformat
     145--------------
     146
     147Converts a byte count into a human readable string like "2Mb". Accepts an
     148optional ``precision`` parameter which defaults to 2.
     149
     150Examples:
     151
     152    * ``3352576`` becomes ``3.20mb``
     153    * ``623394`` becomes ``608.78kb``
     154
    144155ordinal
    145156-------
    146157
Back to Top