How to get average to work with numbers that have a comma

How to get average to work with numbers that have a comma

smasonsmason Posts: 25Questions: 11Answers: 0

Consider the following snippet inside a footer callback.

"footerCallback": function(row, data, start, end, display) {
  var api = this.api();
api.columns('.avg', {
                page: 'current'
          }).every(function() {
                var avg = this.data().average();
                avg = avg.toFixed(2);

         $(this.footer()).html("" + avg + "%");
          });

It seems to return NaN if a value in one of the cells it's looking at contains a comma. How do I remove the comma so that the average function works correctly?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,083Questions: 26Answers: 4,908
    Answer ✓

    You could use the replace function similar to this example:
    https://datatables.net/examples/advanced_init/footer_callback.html

    Kevin

  • smasonsmason Posts: 25Questions: 11Answers: 0

    I modified the intVal function to my needs, just to remove the comma.
    Calculating the average was a little tricky because you have to get the length of the dataset as the denominator. Maybe this could help someone else too.

            "footerCallback": function(row, data, start, end, display) {
                     var api = this.api();
    
                    // Remove the comma to get data for summation
                    var intVal = function ( i ) {
                        return typeof i === 'string' ?
                            i.replace(/,/g,'')*1 :
                                typeof i === 'number' ?
                                           i : 0;
                    };
    
        api.columns('.avg', {
                    page: 'current'
                  }).every(function() {
    
                var numerator = this
                            .data()
                            .reduce( function(a, b) {
                                    return (intVal(a) + intVal(b));
                            }, 0);
    
                var denominator = this.data().length;
    
                avg = numerator / denominator;
                avg = avg.toFixed(2)
    
                $(this.footer()).html(avg);
            });
    
This discussion has been closed.