from django import template

register = template.Library()


@register.filter
def price(v):
    return '{:.2f}€'.format(v)


@register.filter
def diff(v, template='{:+.2f}{}', suffix=''):
    return template.format(v, suffix)


@register.filter
def int_diff(v):
    return diff(v, template='{:+.0f}{}')


@register.filter
def price_diff(v):
    return diff(v, suffix='€')


@register.filter(name='round')
def _round(v, precision=1):
    tpl = '{{:.{}f}}'.format(precision)
    return tpl.format(v)


@register.filter
def percent(v):
    return format(v, '.0%')


@register.filter
def human_round(v, precision=2):
    """ Displaying only <precision> meaningful digits,

    Also remove trailing zeroes
    """
    if v == 0:
        return str(int(0))
    else:
        _v = _round(v, 10)
        int_part, decimal_part = _v.split('.')
        if int(int_part) == 0:
            reached_precision = 0
        else:
            reached_precision = len(int_part)

        decimal_count = 0

        for idx, dec in enumerate(decimal_part):
            if reached_precision >= precision:
                break

            decimal_count += 1
            if not ((reached_precision == 0) and (dec == '0')):
                reached_precision += 1
    return str(round(v, decimal_count)).rstrip('0').rstrip('.')
