Ticket #3004: floatformat.4.diff

File floatformat.4.diff, 2.4 KB (added by real.human@…, 18 years ago)
  • django/template/defaultfilters.py

     
    2727    from django.utils.html import fix_ampersands
    2828    return fix_ampersands(value)
    2929
    30 def floatformat(text):
     30def floatformat(text, precision=1):
    3131    """
    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.
    3434    """
    3535    try:
    3636        f = float(text)
    3737    except ValueError:
    3838        return ''
    39     m = f - int(f)
    40     if m:
    41         return '%.1f' % f
    42     else:
    43         return '%d' % int(f)
     39    return re.sub(r'\.?0+$', '', str(round(f, precision)))
    4440
    4541def linenumbers(value):
    4642    "Displays text with line numbers"
  • tests/regressiontests/defaultfilters/tests.py

     
    88>>> floatformat(0.07)
    99'0.1'
    1010>>> floatformat(0.007)
    11 '0.0'
     11'0'
    1212>>> floatformat(0.0)
    1313'0'
     14>>> floatformat(10.0)
     15'10'
     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'
    1424
    1525>>> addslashes('"double quotes" and \'single quotes\'')
    1626'\\"double quotes\\" and \\\'single quotes\\\''
  • docs/templates.txt

     
    924924floatformat
    925925~~~~~~~~~~~
    926926
    927 Rounds a floating-point number to one decimal place -- but only if there's a
    928 decimal part to be displayed. For example:
     927Rounds a floating-point number to the number of decimal places given in the
     928argument (the dafault is 1), with trailing zeroes and periods stripped.
    929929
    930     * ``36.123`` gets converted to ``36.1``
    931     * ``36.15`` gets converted to ``36.2``
    932     * ``36`` gets converted to ``36``
     930Example:
    933931
     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
    934937get_digit
    935938~~~~~~~~~
    936939
Back to Top