Format sum result with comma - Jquery

1

I'm making a sum of all values for a column in a table.

Returning par to html, is being returned without the comma.

How can I make the comma appear in the second house?

var valor_recibo = 0;

$(".valor_recibo").each(function() {
  var num = parseInt($(this).text().replace(/[^0-9]/g, ''));
  valor_recibo += num;
});

$('#totalrecibo').html(valor_recibo);

The value is returned in a span like this: 25998 Being that the correct form is like this: 259,98

Html Code

<table class="table table-striped m-table m-table--head-bg-success">
  <thead>
    <tr>
      <th>Valor Recibo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="valor_recibo">100</td>
      <td class="valor_recibo">200</td>
      <td class="valor_recibo">300</td>
      <td class="valor_recibo">400</td>
      <td class="valor_recibo">500</td>
    </tr>

  </tbody>
</table>
<div id="totalrecibo"> aqui retorna o valor </div>
    
asked by anonymous 12.06.2018 / 02:49

1 answer

2

parseInt will prevent you from working with decimals. Instead, use parseFloat .

Your replace is also wrong. If in td has only numbers, make a replace by replacing only the comma. JavaScript considers decimal places whatever comes to the right of the dot, not the comma.

At the end of the calculation, you need to convert the result to string and replace the period with the comma:

var valor_recibo = 0;

$(".valor_recibo").each(function() {
  var num = parseFloat($(this).text().replace(',', '.'));
  valor_recibo += num;
});

$('#totalrecibo').html(valor_recibo.toString().replace('.', ','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="table table-striped m-table m-table--head-bg-success">
  <thead>
    <tr>
      <th>Valor Recibo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="valor_recibo">224,30</td>
      <td class="valor_recibo">237,60</td>
      <td class="valor_recibo">194,41</td>
    </tr>

  </tbody>
</table>
<div id="totalrecibo"> aqui retorna o valor </div>
    
12.06.2018 / 04:22