Ticket #5748: 5478.django.template.defaultfilter.diff

File 5478.django.template.defaultfilter.diff, 2.3 KB (added by Pete Crosier, 17 years ago)
  • django/template/defaultfilters.py

     
    11"""Default variable filters."""
    22
     3try:
     4    from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
     5except ImportError:
     6    from django.utils._decimal import Decimal, InvalidOperation, ROUND_HALF_UP
     7
    38import re
    49import random as random_module
    510
     
    4146# STRINGS         #
    4247###################
    4348
    44 
    4549def addslashes(value):
    4650    """
    4751    Adds slashes before quotes. Useful for escaping strings in CSV, for
     
    113117    * {{ num3|floatformat:"-3" }} displays "34.260"
    114118    """
    115119    try:
    116         f = float(text)
    117     except (ValueError, TypeError):
     120        d = Decimal(str(text))
     121    except InvalidOperation:
    118122        return u''
    119123    try:
    120         d = int(arg)
     124        arg = int(arg)
    121125    except ValueError:
    122         return force_unicode(f)
    123     m = f - int(f)
    124     if not m and d < 0:
    125         return mark_safe(u'%d' % int(f))
     126        return force_unicode(d)
     127    if not int(d) - d and arg < 0:
     128        return mark_safe(u'%d' % (int(d)))
     129    if arg == 0:
     130        exp = Decimal(1)
    126131    else:
    127         formatstr = u'%%.%df' % abs(d)
    128         return mark_safe(formatstr % f)
     132        exp = Decimal('1.0') / (Decimal(10) ** abs(arg))
     133    try:
     134        return mark_safe(u'%s' % str(d.quantize(exp, ROUND_HALF_UP)))
     135    except InvalidOperation:
     136        return force_unicode(d)
    129137floatformat.is_safe = True
    130138
    131139def iriencode(value):
  • tests/regressiontests/defaultfilters/tests.py

     
    1313u'0.0'
    1414>>> floatformat(0.0)
    1515u'0'
    16 >>> floatformat(7.7,3)
     16>>> floatformat(7.7, 3)
    1717u'7.700'
    18 >>> floatformat(6.000000,3)
     18>>> floatformat(6.000000, 3)
    1919u'6.000'
    2020>>> floatformat(6.200000, 3)
    2121u'6.200'
    2222>>> floatformat(6.200000, -3)
    2323u'6.200'
    24 >>> floatformat(13.1031,-3)
     24>>> floatformat(13.1031, -3)
    2525u'13.103'
    2626>>> floatformat(11.1197, -2)
    2727u'11.12'
     
    3131u'11.00'
    3232>>> floatformat(8.2798, 3)
    3333u'8.280'
     34>>> floatformat(18.125, 2)
     35u'18.13'
    3436>>> floatformat(u'foo')
    3537u''
    3638>>> floatformat(13.1031, u'bar')
Back to Top