Code

Ticket #3004: floatformat.diff

File floatformat.diff, 1.8 KB (added by real.human@…, 7 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+$', '', ('%%.%sf' % precision) % f)
27 
28 def linenumbers(value):
29     "Displays text with line numbers"
30Index: docs/templates.txt
31===================================================================
32--- docs/templates.txt  (revision 4053)
33+++ docs/templates.txt  (working copy)
34@@ -924,13 +924,16 @@
35 floatformat
36 ~~~~~~~~~~~
37 
38-Rounds a floating-point number to one decimal place -- but only if there's a
39-decimal part to be displayed. For example:
40+Rounds a floating-point number to the number of decimal places given in the
41+argument (the dafault is 1), with trailing zeroes and periods stripped.
42 
43-    * ``36.123`` gets converted to ``36.1``
44-    * ``36.15`` gets converted to ``36.2``
45-    * ``36`` gets converted to ``36``
46+Example:
47 
48+    * ``{{ "36.12345"|floatformat:2 }}`` displays ``36.12``
49+    * ``{{ "36.123"|floatformat }}`` displays ``36.1``
50+    * ``{{ "36.15"|floatformat }}`` displays ``36.2``
51+    * ``{{ "36"|floatformat }}`` displays ``36``
52+
53 get_digit
54 ~~~~~~~~~
55