Search code examples
javascriptdatatables

Sum of values in a table column with different currency symbol


I have a project where in a table I have numerical values that I want to make the total sum of that column but the problem is that in that column has two types of monetary values that are dollars and soles (local currency of my country) as shown in the image. enter image description here

What I want is to separate those values to only add the totals depending on the currency symbol in this case only the total of the amounts in soles and the total of the amounts in dollars of that column.

I use datatables and so far I have used a code to do the total sum but it sums it in general and I don't know how to split them. I thought about doing a conditional but I don't know how to identify the monetary values.

<script>
$(document).ready(function(){
var table = $('#servicios').DataTable({
 processing: true,
 serverSider: true,
 ordering: true,
 stateSave: true,
 "order": [[ 2, "asc" ]],
});
 //SUM
 //var dollars = 0;
//var soles;

/*var diferencia = table.column(4).data().each(function(d,j){
    if(d == dollars){
         dollars += d;
         $("#dola").text((+dollars));
    }else{
        soles += d;
        $("#sole").text((+soles));
    }
});*/
var arrSalePriceOne = table.column(4).data().sum();
$("#tblProfit").text((+arrSalePriceOne));

Solution

  • You need to split the data and check the symbol like this,

    let soles = 0.0;
    let dollar = 0.0;
    
    table.column(4).data().each( value => {
    
      // value would be S/ 23.3 OR $ 23.3
    
      const [symbol, amount] = value.split(' '); // split by space
    
      if (symbol === "S/") {
        soles += parseFloat(amount);
      } else if (symbol === "$") {
        dollar += parseFloat(amount);
      } else {
       
        // whatever if none of above
    
      }
    
    });