数学使用Django模板过滤器? [英] Do math using Django template filter?

查看:94
本文介绍了数学使用Django模板过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我有一个整数字段存储价格信息,如10399,84700。
显示时,它们应该是$ 103.99和$ 847.00。



我需要显示int * 0.01。



我想知道是否有办法使用Django模板过滤器?喜欢:

  {{item.price | int_to_float_and_times_0.01}} 
另外还有一个问题,我选择了整数,因为我觉得比在数据库中使用float更有效率。这是真的吗?

解决方案

您可以使自己的模板过滤器基本上完成所需要的只是将输入除以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.

这篇关于数学使用Django模板过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆