from django import template

register = template.Library()

@register.filter
def numberize(number):
    """
    return convert number to string, an example:
        - 1000 to 1k
        - 1000000 to 1m, etc.
    :param `number` is number to convert.

    usage:
        {{ post.get_visitors.count|numberize }}
    """
    scales = {
        1000: 'k',
        1000000: 'm',
        1000000000: 'b',
        1000000000000: 't',
        1000000000000000: 'quad',
        1000000000000000000: 'quin',
        1000000000000000000000: 'sexti',
        1000000000000000000000000: 'septi',
        1000000000000000000000000000: 'octi',
        1000000000000000000000000000000: 'noni',
        1000000000000000000000000000000000: 'deci',
        1000000000000000000000000000000000000: 'undeci',
        1000000000000000000000000000000000000000: 'duodeci',
        1000000000000000000000000000000000000000000: 'trede',
        1000000000000000000000000000000000000000000000: 'quattu',
        1000000000000000000000000000000000000000000000000: 'quindeci',
        1000000000000000000000000000000000000000000000000000: 'sexdeci',
        1000000000000000000000000000000000000000000000000000000: 'septend',
        1000000000000000000000000000000000000000000000000000000000: 'octodeci',
        1000000000000000000000000000000000000000000000000000000000000: 'novemdeci',
        1000000000000000000000000000000000000000000000000000000000000000: 'vigintillion',
        1000000000000000000000000000000000000000000000000000000000000000000: 'infinity'
    }

    try:
        number = int(number)
    except ValueError:
        return number

    for digit, name in scales.items():
        minimum = '9' * len(str(digit)[1:])
        maximum = minimum + '999'

        if number > max(scales):
            return "{0:.1f} ".format(number / max(scales)) + name

        elif number > int(minimum) and number <= int(maximum):
            return "{0:.1f} ".format(number / digit) + name
    return number

"""
print(numberize(10))                    # 10
print(numberize(2222))                  # 2.2 k
print(numberize(3919393))               # 3.9 m
print(numberize(2147483647))            # 2.1 b
print(numberize(2347483648887))         # 2.3 t
print(numberize(9223372036854775807))   # 9.2 quin
"""