Login

django smartround filter

Author:
bmarchenko
Posted:
March 14, 2017
Language:
Python
Version:
Not specified
Tags:
smart round smartfloatformat
Score:
0 (after 0 ratings)
rounds floats in more human readable format e.g.
341.123434 mUSD -> 341mUSD
0.45345345 mUSD -> 0.5 mUSD
0.034545 mUSD -> 0.03 mUSD
0.0014545 mUSD -> 0.001 mUSD
etc.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@register.filter(is_safe=True)
def smartround(num):
    """
    rounds floats in more human readable format
    e.g.
    341.123434 mUSD -> 341mUSD
    0.45345345 mUSD -> 0.5mUSD
    0.034545 mUSD -> 0.03mUSD
    0.0014545 mUSD -> 0.001mUSD
    etc.
    """
    if isinstance(num, float):
        whole_part, dec_part = str(num).split(".")
        whole_part_len = len(whole_part)
        if whole_part_len > 3:
            return int(num)
        else:
            try:
                round_to = re.search(r'[^0]', dec_part).start()
                return round(num, round_to+1)
            except AttributeError:
                return int(num)
    return num

More like this

Comments

Please login first before commenting.