Solved

Adding Decimals Using the Add Filter

  • 14 August 2023
  • 1 reply
  • 75 views

Badge

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?

icon

Best answer by davref 14 August 2023, 19:53

View original

1 reply

Badge

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. 

Reply