Code

Ticket #3004: floatformat.3.diff

File floatformat.3.diff, 2.2 KB (added by real.human@…, 8 years ago)
Line 
1Index: django/template/defaultfilters.py
2===================================================================
3--- django/template/defaultfilters.py   (revision 4053)
4+++ django/template/defaultfilters.py   (working copy)
5@@ -27,20 +27,16 @@
6     from django.utils.html import fix_ampersands
7     return fix_ampersands(value)
8 
9-def floatformat(text):
10+def floatformat(text, precision=1):
11     """
12-    Displays a floating point number as 34.2 (with one decimal place) -- but
13-    only if there's a point to be displayed
14+    Rounds a floating point number to the number of decimal places given in the
15+    argument, with trailing zeroes and periods stripped.
16     """
17     try:
18         f = float(text)
19     except ValueError:
20         return ''
21-    m = f - int(f)
22-    if m:
23-        return '%.1f' % f
24-    else:
25-        return '%d' % int(f)
26+    return re.sub(r'\.?0+$', '', str(round(f, precision)))
27 
28 def linenumbers(value):
29     "Displays text with line numbers"
30Index: tests/regressiontests/defaultfilters/tests.py
31===================================================================
32--- tests/regressiontests/defaultfilters/tests.py       (revision 4053)
33+++ tests/regressiontests/defaultfilters/tests.py       (working copy)
34@@ -8,7 +8,7 @@
35 >>> floatformat(0.07)
36 '0.1'
37 >>> floatformat(0.007)
38-'0.0'
39+'0'
40 >>> floatformat(0.0)
41 '0'
42 
43Index: docs/templates.txt
44===================================================================
45--- docs/templates.txt  (revision 4053)
46+++ docs/templates.txt  (working copy)
47@@ -924,13 +924,16 @@
48 floatformat
49 ~~~~~~~~~~~
50 
51-Rounds a floating-point number to one decimal place -- but only if there's a
52-decimal part to be displayed. For example:
53+Rounds a floating-point number to the number of decimal places given in the
54+argument (the dafault is 1), with trailing zeroes and periods stripped.
55 
56-    * ``36.123`` gets converted to ``36.1``
57-    * ``36.15`` gets converted to ``36.2``
58-    * ``36`` gets converted to ``36``
59+Example:
60 
61+    * ``{{ "36.12345"|floatformat:2 }}`` displays ``36.12``
62+    * ``{{ "36.123"|floatformat }}`` displays ``36.1``
63+    * ``{{ "36.15"|floatformat }}`` displays ``36.2``
64+    * ``{{ "36"|floatformat }}`` displays ``36``
65+
66 get_digit
67 ~~~~~~~~~
68