"""
    A filter to format negative number.

    Sometimes one want to display negative number differently then
    just using a negative sign.

    Call with optional argument, specify one or more of:
    negativeformat:"negative_prefix,negative_suffix,normal_prefix,normal_suffix"

    If value is negative, the value's negatve sign will be removed,
    and then wrapped between negative_prefix and negative_suffix.

    If value is positive, the value is simply
    wrapped between negative_prefix and negative_suffix.

    See doctests below for examples:


    # replace negative sign with parenthsis
    >>> print negativeformat('100')
    100

    >>> print negativeformat('-100')
    (100)

    >>> print negativeformat('0')
    0


    # replace negative sign with parenthsis, and prepend dollar sign
    >>> print negativeformat('100',arg='($,),$')
    $100

    >>> print negativeformat('-100',arg='($,),$')
    ($100)

    # replace negative sign with parenthsis, and append percentage sign
    >>> print negativeformat('100',arg='(,%),,%')
    100%

    >>> print negativeformat('-100',arg='(,%),,%')
    (100%)

    # silly example, we just want to prepend a dollar sign.
    >>> print negativeformat('100',arg='$,,$')
    $100

    >>> print negativeformat('-100',arg='$-,,$')
    $-100

"""
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def negativeformat(value, arg='(,)'):
    """
    A filter to format negative number.
    """
    # process arg: prefix and suffix for negative case, prefix and suffix for positive case.
    # All can be optional.
    args = arg.split(',')

    prefix = suffix = ''
    neg_prefix = neg_suffix = ''

    # fill args out to four, with default values
    extras = ['' for i in range(4-len(args))]
    args.extend(extras)

    neg_prefix, neg_suffix ,prefix, suffix = args

    if len(value) == 0:
        return value
    if value[0] == '-':
        return '%s%s%s' % (neg_prefix, value[1:], neg_suffix)
    else:
        return '%s%s%s' % (prefix, value, suffix)


if __name__ == '__main__':
    import doctest
    doctest.testmod()