简体   繁体   中英

Twig doesn't approximate number

I have a strange situation. My code is :

{% set total_amount=0 %}
{% for result in a_result %}
   <tr>
      <td>{% set total_amount=total_amount+("%.2f"|format(result.tva*result.prix_ht)) %}
      {{ "%.2f"|format(result.tva*result.prix_ht) }}
      </td>
   /tr>
 {% endfor %}
 <tr>
     <td colspan="5">Total</td>
     <td>{{ total_amount }}</td>
 </tr>

As result I have : 15.98, 25.49, 25.49 And Total = 65 but total should be equal with 65.96 . I don't understand where is the problem. Can you help me please ?

I suggest you to use the round and number_format filter as follow:

{% set total_amount=0 %}
{% for result in a_result %}
{% set value = (result.tva* result.prix_ht)|round(2) %}
{% set total_amount=total_amount+value %}
   <tr>
      <td>
      {{ value|number_format(2, '.', ',') }}
      </td>
   /tr>
 {% endfor %}
 <tr>
     <td colspan="5">Total</td>
     <td>{{ total_amount|number_format(2, '.', ',') }}</td>
 </tr>

A running example with sample data in this twigfiddle files

Hope this help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM