Skip to main content
Contributor I
August 14, 2023
Solved

Adding Decimals Using the Add Filter

  • August 14, 2023
  • 1 reply
  • 210 views

Hello!

I’m attempting to add two variables using the add filter and then multiple the result

{{item.options.price|add:item.unit_price|multiply:item.quantity|floatformat:2}}

This works fine if both item.options.price and item.unit_price are whole numbers. If one is a decimal, the addition does not happen. 

I’ve also tried a simplified version

{{item.unit_price|add:0.25}}

And only the item.unit_price is shown without 0.25 added. 

Can the add filter handle decimals?

    This topic has been closed for replies.
    Best answer by davref

    After some more digging, it looks like the add filter coerces both values to integers: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#add

    If you are trying to add a constant decimal (like 0.25) to a variable, you can probably do something like this: 

    {{item.unit_price|multiply:100|add:25|divide:100}}

    But this approach won’t work for adding two variables together. 

    1 reply

    davrefAuthorAnswer
    Contributor I
    August 14, 2023

    After some more digging, it looks like the add filter coerces both values to integers: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#add

    If you are trying to add a constant decimal (like 0.25) to a variable, you can probably do something like this: 

    {{item.unit_price|multiply:100|add:25|divide:100}}

    But this approach won’t work for adding two variables together.