从传递给 django 模板的数字中删除小数点



我正在使用 stripe 通过 django Web 应用程序处理付款。

数据库中的价格以十进制格式存储,例如 100.00

Stripe 将其视为 1 美元,并忽略小数点右侧的所有内容。

将此数字传递给 Stripe 时,我需要删除小数点。

我可以在 django 模板中执行此操作吗?

使用 FLoat 格式过滤器,您可以这样做:

{{ value.context|floatformat }}

编辑

特别有用的是传递 0(零)作为参数,它将浮点数舍入到最接近的整数。

value       Template                        Output
34.23234    {{ value|floatformat:"0" }}     34
34.00000    {{ value|floatformat:"0" }}     34
39.56000    {{ value|floatformat:"0" }}     40
我认为

您可以在模板中使用自定义过滤器,如下所示:

from django import template
register = template.Library()
@register.filter
def remove_decimal_point(value):
    return value.replace(".","")

并在模板中使用它,如下所示:

{% load remove_decimal_point %}
....
{{ val|remove_decimal_point }}

这有点取决于您的实现。这样的事情应该在所有情况下都有效:

total_price = 123.4567
stripe_price = str(int(round(total_price, 2) * 100))

这会产生:

'12346'

这首先舍入到两位小数,乘以 100 并转换为整数,然后是字符串。根据您的 Stripe 集成,您可以跳过转换为整数和字符串。

跳过转换到 int 将产生如下结果:

>> str(round(total_price, 2) * 100)
>> '12346.00'

它仍然有效,因为 Stripe 会去除小数点后的所有内容,但也许您不想要那些尾随的零。

如果要在模板中转换数字,则可以选择使用自定义模板过滤器,正如其他人已经指出的那样。

@register.filter(name='stripeconversion')
def stripe_value(total_price):
    return str(int(round(total_price, 2) * 100))

并在模板中使用它:

{{ total_price|stripeconversion }}

最新更新