user10592228
user10592228

Reputation:

how to set decimal value of (2) js datatables

Im trying to set my decimal numbers to two(2) but I cannot succeed. Any help would be appreciated. I am calculating the average number per column view and average total of all the column. The problem I'm facing is, that I have up to 14 position after the decimal point and I would like to reduce this to (2) only. I am working with Datatables and there is indicated the use of .toFixed(2). I tried but can not work it out. please see below and the fiddle

I provided a jsfiddle for my situation.

Thank you in advance

$('#dtcuidadhrs').DataTable({
responsive: true,
"footerCallback": function(tfoot, data, start, end, display) {
    var api = this.api();

    for (var i = 0; i < api.columns().count(); i++) {

        var columnDataTotal = api
            .column(i)
            .data();
        var theColumnTotal = columnDataTotal
            .reduce(function(a, b) {
                if (isNaN(a)) {
                    return '';
                } else {
                    a = parseFloat(a);
                }
                if (isNaN(b)) {
                    return '';
                } else {
                    b = parseFloat(b);
                }
                return (a + b).toFixed(2);
            }, 0);

        var columnData = api
           .column( i, { page: 'current'} )
           .data()
        var theColumnPage = columnData
            .reduce(function(a, b) {
                if (isNaN(a)) {
                    return '';
                } else {
                    a = parseFloat(a);
                }
                if (isNaN(b)) {
                    return '';
                } else {
                    b = parseFloat(b);
                }
                return (a + b).toFixed(2);
            }, 0);

        // Update footer
        $( api.column( 0 ).footer() ).html('Avarage');
        $(api.column(i).footer()).html(
            theColumnPage / columnData.count() + ' ('+ theColumnTotal / columnDataTotal.count() +' Total)'
        );
    }
}
});

Upvotes: 0

Views: 962

Answers (1)

Neal
Neal

Reputation: 673

Looking at the JS fiddle, you are running a reduce to sum the average of each column using toFixed.

When doing calculations, it's best to only round on the very final number (otherwise loss of precision is a serious concern). Try the following: I would refactor a bit, but you get the idea

// Update footer
            $( api.column( 0 ).footer() ).html('Avarage');
            $(api.column(i).footer()).html(
                theColumnPage / columnData.count() + ' ('+ parseFloat(theColumnTotal / columnDataTotal.count()).toFixed(2) +' Total)'

Upvotes: 1

Related Questions