Login

django smartround filter

Author:
bmarchenko
Posted:
March 14, 2017
Language:
Python
Version:
Not specified
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months, 1 week ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.