Remove decimal point from number passed to django template?

Viewed 4612

I am using stripe to process payments with a django web application.

The prices in the database are stored in decimal format, e.g. 100.00

Stripe takes this as $1, and ignores everything to the right of the decimal point.

I need to remove the decimal point when passing this number to Stripe.

Can I do this within the django template?

3 Answers

Using FLoat Format Filter you can do this :

{{ value.context|floatformat }}

EDIT

Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.

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

I think you can use a custom filter in templates, like this:

from django import template

register = template.Library()

@register.filter
def remove_decimal_point(value):
    return value.replace(".","")

And use it in template like this:

{% load remove_decimal_point %}

....

{{ val|remove_decimal_point }}

This depends a little bit on your implementation. Something like this should work in all cases:

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

This produces:

'12346'

This first rounds to two decimals, multiplies by 100 and casts to integer and then string. Depending on your Stripe integration, you could skip casting to integer and string.

Skipping casting to int will produce a result like this:

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

It will still work since Stripe strips everything after decimal, but maybe you don't want those trailing zeros.

If you want to convert numbers inside template, then using custom template filter, as others have already pointed out, is an option.

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

and use it in template:

{{ total_price|stripeconversion }}
Related