Skip to content Skip to sidebar Skip to footer

Do Math Using Django Template Filter?

In my database I have an integer field storing price information, like '10399', '84700'. When display, they should be '$103.99' and '$847.00'. I need int*0.01 to be displayed. I wa

Solution 1:

You could make your own template filter which essentially does what you need by just dividing the input by 100. For example:

in my_app/templatetags/currency_helper.py:

from django import template
register = template.Library()

@register.filterdefto_currency(value):
    returnfloat(value) / 100.0

Then in your template:

{% load currency_helper %}

etc...

{{item.price|to_currency}}

Also, if I were you, I would store currency values in your database as a decimal field to avoid the headache of doing this or dealing with roundoff error.

Solution 2:

You can use the widthratio templatetag for division:

${% widthratio item.price 100 1 %}

(The result is (a/b)*c if a,b,c are the 3 parameters for widthratio)

will result in: $103.99 (for 10399)

Solution 3:

You can simply modify the integers before passing them to the template context, for example with a list comprehension:

context['prices'] = [float(item) * 0.01for item in Model.objects.all()]

(You can also make it a generator by removing the brackets if you Python version supports it, it will make your code use less memory.)

It seems very unlikely that using int instead of float will make you website noticeably faster. If you want a safe type for prices, use decimal: http://docs.python.org/library/decimal.html

Solution 4:

I don't know whether you can return a float, but you can format the number as a string:

from django import template
register = template.Library()

defint_to_float_and_times(value):
  value = float(value) * .01returnu'${0:.2f}'.format(value)

register.filter('int_to_float_and_times', int_to_float_and_times)

How do you define efficient? Usually monetary values are stored in special formats that try to do exact calculations.

edit: 0.01 is not allowed in a function name

Post a Comment for "Do Math Using Django Template Filter?"