Do math using a Django template filter?

In my database, I have a whole field that stores price information, for example, "10399", "84700". When displayed, they should be "$ 103.99" and "$ 847.00."

I need to show int * 0.01.

I was wondering if there is a way to do this using a Django template filter? How:

{{ item.price|int_to_float_and_times_0.01 }} 

Another question, in fact, I chose an integer, because I thought it would be more efficient than using float in the database. It's true?

+1
source share
4 answers

You can create your own template filter, which essentially does what you need by simply dividing the input by 100. For example:

in my_app / templatetags / currency_helper.py:

 from django import template register = template.Library() @register.filter def to_currency(value): return float(value) / 100.0 

Then in your template:

 {% load currency_helper %} etc... {{item.price|to_currency}} 

In addition, if I were you, I would save the currency values ​​in your database as a decimal field to avoid a headache when doing this or with a rounding error.

+7
source

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

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

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

It seems very unlikely that using int instead of float will make your site noticeably faster. If you need a safe pricing type, use decimal : http://docs.python.org/library/decimal.html

0
source

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

 from django import template register = template.Library() def int_to_float_and_times(value): value = float(value) * .01 return u'${0:.2f}'.format(value) register.filter('int_to_float_and_times', int_to_float_and_times) 

How do you measure effectiveness? Typically, monetary values ​​are stored in special formats that attempt to perform accurate calculations.

edit: 0.01 not allowed in function name

0
source

You can use widthratio templatetag for division:

 ${% widthratio item.price 100 1 %} 

(Result (a / b) * c, if a, b, c - 3 parameters for widthratio )

will result in: $103.99 (for 10399)

0
source

All Articles