Format summation result with comma - Jquery

Asked

Viewed 623 times

1

I am making a sum of all the values related to a column of a table.

When returning even to html, it is being returned without the comma.

How can I proceed so that the comma is presented 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 The correct form is: 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>

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

  • 1

    parseint converts to integer. exchange for parseFloat.

  • I performed the exchange. but it still holds value without the comma.

  • 1

    But then you have to see what you’re adding up. What values are you adding up?

  • I am adding several <td class="receipt value_value">.

  • you would like me to post html code ?

  • 1

    It would be interesting.

  • 1

    I imagine the problem is in the regular expression. Try to change /[^0-9]/g for /[^0-9,]/g.

Show 4 more comments

1 answer

2


The parseInt prevent you from working with decimal places. Instead, use parseFloat.

Also his replace is wrong. If in td has only numbers, make a replace replacing only the comma. Javascript considers decimal places to the right of the dot, not the comma.

At the end of the calculation, you still need to convert the result to string and replace the point 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>
<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">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>

  • 1

    Problem solved. Thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.