-1

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

DarkBee
  • 16,592
  • 6
  • 46
  • 58
mins
  • 3
  • 3

1 Answers1

0

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

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • Thank you so much! You are the first person who ever answered this question in the past 2 months! However, it only printed the result when I added number_format. So I modified as {% set net_cost = 0 %} {% for item in data.item %} {% set total_qty = (item.qty)|number_format(2,'.',',') %} {% set per_price = (item.total)|number_format(2,'.',',') %} {% set net_cost = net_cost + (total_qty * per_price ) %} {% endfor %} {{ '$ ' ~ net_cost }} and it worked. Do you know why I shouldn't put number_format? – mins Feb 01 '22 at 21:21
  • If you use `number_format` beforehand, you can end up with rounding errors – DarkBee Feb 02 '22 at 06:23