Skip to content

Latest commit

 

History

History
45 lines (33 loc) · 1.12 KB

20240103205736.md

File metadata and controls

45 lines (33 loc) · 1.12 KB

Custom Django template filter for currency conversion

  1. Write your filter in app/templatetags/tags.py:
from decimal import Decimal

from django import template

register = template.Library()


@register.filter(name="convert_currency")
def convert_currency(value, rate):
    """
    Converts the given amount to a different currency using the specified rate.
    Usage: {{ value|convert_currency:rate }}
    """
    try:
        value = Decimal(value)
        rate = Decimal(rate)
        return round(value * rate, 2)
    except (ValueError, TypeError, Decimal.InvalidOperation):
        return value
  1. Use it in your template HTML. The "value" (here amount) gets piped into the filter (like in Unix), and any arguments (here rate) are added after the colon:

{{ amount }} USD ({{ amount|convert_currency:rate }} AUD)


Note that it's recommended to use Decimal here, because:

# Using floats
total = 0.1 + 0.1 + 0.1
print(total)  # Expected: 0.3, Actual: 0.30000000000000004

# Using Decimal
from decimal import Decimal
total = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
print(total)  # Exactly 0.3

#django