且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数学使用Django模板过滤器?

更新时间:2023-10-25 22:27:40

您可以使自己的模板过滤器基本上完成所需要的只是将输入除以100。例如:



在my_app / templatetags / currency_helper.py中:

 从django导入模板
register = template.Library()

@ register.filter
def to_currency(value):
return float(value)/ 100.0

然后在您的模板中:

  {%load currency_helper%} 

etc ...

{{item.price | to_currency}}

此外,如果我是你,我将货币值存储在数据库中作为一个十进制字段,以避免头痛做这个或处理舍入误差。


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?

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.