Skip to main content
Solved

Adding Decimals Using the Add Filter

  • August 14, 2023
  • 1 reply
  • 149 views

Forum|alt.badge.img+1

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?

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. 

View original
Did this topic or the replies in the thread help you find an answer to your question?

1 reply

Forum|alt.badge.img+1
  • Author
  • Contributor I
  • 1 reply
  • Answer
  • 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.