devfeng
devfeng

Reputation: 291

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 was wondering if there is a way to do it using Django template filter? Like:

{{ item.price|int_to_float_and_times_0.01 }}

Another question, actually I chose integer because I thought it would be more efficient than using float in database. Is that true?

Upvotes: 2

Views: 6785

Answers (4)

manji
manji

Reputation: 47968

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)

Upvotes: 1

Gauchi
Gauchi

Reputation: 101

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()

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 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

Upvotes: 0

Bastien Léonard
Bastien Léonard

Reputation: 61833

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

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 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

Upvotes: 0

ryanshow
ryanshow

Reputation: 562

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.filter
def to_currency(value):
    return float(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.

Upvotes: 8

Related Questions