How to calculate the composite's elements and get total of them?

225 Views Asked by At

Hi I have a composite that has a QTY field and a TOTAL PRICE field and the table below would calculate and display the subtotal. It works properly when there is only one row of composite, but when I add more items, the subtotal field displays two subtotals instead of one as a whole. I want the subtotal field to display 24 instead of 4 and 20. How can twig solve this implementation? In my SUBTOTAL, I have

    {% for item in data.item %} 
    {% set total_qty = (item.qty)|number_format(2,'.',',') %} 
    {% set per_price = (item.total)|number_format(2,'.',',') %} 
    {% set net_cost = (total_qty * per_price )|number_format(2,'.',',') %} 
    {{ net_cost }} 
    {% endfor %}

Here is the screenshot to give you better understanding

1

There are 1 best solutions below

2
DarkBee On BEST ANSWER

Don't output the net cost inside the for loop. First create the sum, then display it after the loop.
Also don't use number_format before the final result.

{% set net_cost = 0 %}
{% for item in data.items %}
    {% set net_cost = nest_cost + item.qty * item.total %}
{% endfor %}

{{ net_cost|number_format(2, '.', ',') }}

demo