Monday, September 12, 2011

Formatting floats in Python

Not really straightforward since there are number of issues. In this SO question, Alex Martelli simply suggested using the rstrip() string method to remove the zero. Others suggested the "g" flag, such as "%.1g". One issue with "g" flag is if the number to be formatted is larger than the format width specify, it would display it in scientific notation. It can be fixed by using large enough width such as "%.99g".

Django has floatformat template filter and it seem to use different approach in django.core.template.defaultfilters
def floatformat(text):
    """
    Displays a floating point number as 34.2 (with one decimal place) -- but
    only if there's a point to be displayed
    """
    try:
        f = float(text)
    except ValueError:
        return ''
    m = f - int(f)
    if m:
        return '%.1f' % f
    else:
        return '%d' % int(f)

No comments: