Ticket #3004: floatformat.5.diff
File floatformat.5.diff, 2.8 KB (added by mrmachine <real.human@…>, 9 years ago) 


django/template/defaultfilters.py
27 27 from django.utils.html import fix_ampersands 28 28 return fix_ampersands(value) 29 29 30 def floatformat(text ):30 def floatformat(text, precision=1): 31 31 """ 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 Rounds a floating point number to the number of decimal places given in the 33 argument, with trailing zeroes and periods stripped. Uses the decimal module 34 for accurate rounding. 34 35 """ 36 from decimal import Decimal, InvalidOperation 35 37 try: 36 f = float(text) 37 except ValueError: 38 text = str(text) 39 precision = int(precision) 40 exponent = Decimal(10) **  precision 41 number = Decimal(text).quantize(exponent) 42 except (InvalidOperation, TypeError, ValueError): 38 43 return '' 39 m = f  int(f) 40 if m: 41 return '%.1f' % f 42 else: 43 return '%d' % int(f) 44 return re.sub(r'\.?0+$', '', str(number)) 44 45 45 46 def linenumbers(value): 46 47 "Displays text with line numbers" 
tests/regressiontests/defaultfilters/tests.py
8 8 >>> floatformat(0.07) 9 9 '0.1' 10 10 >>> floatformat(0.007) 11 '0 .0'11 '0' 12 12 >>> floatformat(0.0) 13 13 '0' 14 >>> floatformat(0) 15 '0' 16 >>> floatformat(3.14159, 2) 17 '3.14' 18 >>> floatformat(0.0, 2) 19 '0' 20 >>> floatformat(1.1, 2) 21 '1.1' 22 >>> floatformat(1.017, 2) 23 '1.02' 24 >>> floatformat(0.1234567, 4) 25 '0.1235' 14 26 15 27 >>> addslashes('"double quotes" and \'single quotes\'') 16 28 '\\"double quotes\\" and \\\'single quotes\\\'' 
docs/templates.txt
924 924 floatformat 925 925 ~~~~~~~~~~~ 926 926 927 Rounds a floatingpoint number to one decimal place  but only if there's a928 decimal part to be displayed. For example: 927 Rounds a floatingpoint number to the number of decimal places given in the 928 argument (the dafault is 1), with trailing zeroes and periods stripped. 929 929 930 * ``36.123`` gets converted to ``36.1`` 931 * ``36.15`` gets converted to ``36.2`` 932 * ``36`` gets converted to ``36`` 930 Example: 933 931 932 * ``{{ "36.12345"floatformat:2 }}`` displays ``36.12`` 933 * ``{{ "36.123"floatformat }}`` displays ``36.1`` 934 * ``{{ "36.15"floatformat }}`` displays ``36.2`` 935 * ``{{ "36"floatformat }}`` displays ``36`` 936 934 937 get_digit 935 938 ~~~~~~~~~ 936 939