Ticket #5748: 5478.django.template.defaultfilter.diff
File 5478.django.template.defaultfilter.diff, 2.3 KB (added by , 17 years ago) |
---|
-
django/template/defaultfilters.py
1 1 """Default variable filters.""" 2 2 3 try: 4 from decimal import Decimal, InvalidOperation, ROUND_HALF_UP 5 except ImportError: 6 from django.utils._decimal import Decimal, InvalidOperation, ROUND_HALF_UP 7 3 8 import re 4 9 import random as random_module 5 10 … … 41 46 # STRINGS # 42 47 ################### 43 48 44 45 49 def addslashes(value): 46 50 """ 47 51 Adds slashes before quotes. Useful for escaping strings in CSV, for … … 113 117 * {{ num3|floatformat:"-3" }} displays "34.260" 114 118 """ 115 119 try: 116 f = float(text)117 except (ValueError, TypeError):120 d = Decimal(str(text)) 121 except InvalidOperation: 118 122 return u'' 119 123 try: 120 d= int(arg)124 arg = int(arg) 121 125 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) 126 131 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) 129 137 floatformat.is_safe = True 130 138 131 139 def iriencode(value): -
tests/regressiontests/defaultfilters/tests.py
13 13 u'0.0' 14 14 >>> floatformat(0.0) 15 15 u'0' 16 >>> floatformat(7.7, 3)16 >>> floatformat(7.7, 3) 17 17 u'7.700' 18 >>> floatformat(6.000000, 3)18 >>> floatformat(6.000000, 3) 19 19 u'6.000' 20 20 >>> floatformat(6.200000, 3) 21 21 u'6.200' 22 22 >>> floatformat(6.200000, -3) 23 23 u'6.200' 24 >>> floatformat(13.1031, -3)24 >>> floatformat(13.1031, -3) 25 25 u'13.103' 26 26 >>> floatformat(11.1197, -2) 27 27 u'11.12' … … 31 31 u'11.00' 32 32 >>> floatformat(8.2798, 3) 33 33 u'8.280' 34 >>> floatformat(18.125, 2) 35 u'18.13' 34 36 >>> floatformat(u'foo') 35 37 u'' 36 38 >>> floatformat(13.1031, u'bar')