Ticket #3176: django.template.defaultfilters.py.patch

File django.template.defaultfilters.py.patch, 1.6 KB (added by Eric Floehr <eric@…>, 18 years ago)

Patch to floatformat tag in django.template.defaultfilters

  • django/template/defaultfilters.py

     
    2727    from django.utils.html import fix_ampersands
    2828    return fix_ampersands(value)
    2929
    30 def floatformat(text):
     30def floatformat(text, arg=-1):
    3131    """
    32     Displays a floating point number as 34.2 (with one decimal place) -- but
    33     only if there's a point to be displayed
     32    If called without an argument, displays a floating point
     33    number as 34.2 -- but only if there's a point to be displayed.
     34    With a positive numeric argument, it displays that many decimal places
     35    always.
     36    With a negative numeric argument, it will display that many decimal
     37    places only if there's places to be displayed.
     38    Examples:
     39        num1 = 34.23234
     40        num2 = 34.00000
     41        num1|floatformat results in 34.2
     42        num2|floatformat is 34
     43        num1|floatformat:3 is 34.232
     44        num2|floatformat:3 is 34.000
     45        num1|floatformat:-3 is 34.232
     46        num2|floatformat:-3 is 34
    3447    """
    3548    try:
     49        d = int(arg)
     50    except ValueError:
     51        return text
     52    try:
    3653        f = float(text)
    3754    except ValueError:
    3855        return ''
    3956    m = f - int(f)
    40     if m:
    41         return '%.1f' % f
     57    if not m and d<0:
     58        return '%d' % int(f)
    4259    else:
    43         return '%d' % int(f)
     60        formatstr = '%%.%df' % abs(d)
     61        return formatstr % f
    4462
    4563def linenumbers(value):
    4664    "Displays text with line numbers"
Back to Top