- Author:
- bl4th3rsk1t3
- Posted:
- April 27, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 1 (after 1 ratings)
Takes a float number (23.456) and uses the decimal.quantize to round it to a fixed exponent. This allows you to specify the exponent precision, along with the rounding method. And is perfect for monetary formatting taking into account precision.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import decimal
from django import template
from django.template.defaultfilters import stringfilter
register=template.Library()
@register.filter
def quantize(value,arg=None):
"""
Takes a float number (23.456) and uses the
decimal.quantize to round it to a fixed
exponent. This allows you to specify the
exponent precision, along with the
rounding method.
Examples (assuming value="7.325"):
{% value|quantize %} -> 7.33
{% value|quantize:".01,ru" %} -> 7.33 (this is the same as the default behavior)
{% value|quantize:".01,rd" %} -> 7.32
Available rounding options (taken from the decimal module):
ROUND_CEILING (rc), ROUND_DOWN (rd), ROUND_FLOOR (rf), ROUND_HALF_DOWN (rhd),
ROUND_HALF_EVEN (rhe), ROUND_HALF_UP (rhu), and ROUND_UP (ru)
Arguments cannot have spaces in them.
See the decimal module for more info:
http://docs.python.org/library/decimal.html
"""
num=decimal.Decimal(str(value))
options=["ru","rf","rd","rhd","rhe","rhu"]
precision=None;rounding=None
if arg:
args=arg.split(",")
precision=args[0]
rounding=str(args[1])
if not precision: precision=".01"
if not rounding: rounding=decimal.ROUND_UP
if rounding not in options: rounding=decimal.ROUND_UP
if rounding=="ru":rounding=decimal.ROUND_UP
elif rounding=="rf": rounding=decimal.ROUND_FLOOR
elif rounding=="rd": rounding=decimal.ROUND_DOWN
elif rounding=="rhd": rounding=decimal.ROUND_HALF_DOWN
elif rounding=="rhe": rounding=decimal.ROUND_HALF_EVEN
elif rounding=="rhu": rounding=decimal.ROUND_HALF_UP
newnum=num.quantize(decimal.Decimal(precision),rounding=rounding)
return newnum
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.