Subtotals not working with decimals
Subtotals not working with decimals

Hello,
I attempted to build a test case, but it won't total like on my server.
http://live.datatables.net/bowoceha/1/edit
I thought this was working correctly but I've found that this function doesn't work with decimals. When I total up whole numbers I get a perfect total. When I total anything with a decimal (i.e. 14.26) The function adds it as 1426. I changed the totals line to be formatted to 2 decimal places but have no idea why it would be reading decimals as whole numbers. Any advice would be greatly appreciated.
<script>
$(document).ready(function() {
$('#example').DataTable( {
"paging": false,
order: [[0, 'asc']],
rowGroup: {
startRender: null,
endRender: function ( rows, group ) {
var salaryAvg = rows
.data()
.pluck(4)
.reduce( function (a, b) {
return a + b.replace(/[^\d]/g, '')*1;
}, 0);
salaryAvg = $.fn.dataTable.render.number(',', '.', 2, '$').display( salaryAvg );
var ageAvg = rows
.data()
.pluck(4)
.reduce( function (a, b) {
return a + b*1;
}, 0) / rows.count();
return $('<tr/>')
.append( '<td colspan="3">Total for '+group+'</td>' )
.append( '<td/>' )
.append( '<td>'+salaryAvg+'</td>' );
},
dataSrc: 0
}
} );
} );
</script>
This question has an accepted answers - jump to answer
Answers
The example didn't have all the correct CSS to display correctly. I used the Download Builder to correct this.
I changed the salarAvg column to use column 5 and the ageAvg column to be 3. I changed the regex from
replace(/[^\d]/g, '')
toreplace(/[\$,]/g, '')
. The regex you had removes the decimal. Added a couple console.log debug statements to help troubleshoot. Also updated the salaries to have decimals.Here is the working example:
http://live.datatables.net/cenayiwo/1/edit
Kevin
Kevin,
Thank you so much for the help. It's working now. I'll need to read up on regex for next time.
One quick question though. Your totals are bolded, is that getting it's formatting from the .append in the CSS file?
Thanks again for your help.
You can inspect the rowGroup row and see something like the following:
Notice the CSS:
You can override this if you like and do something like:
For example:
http://live.datatables.net/turagova/1/edit
You could also add your own class to what you append and have that be normal while keeping the rowGroup title (name in this case) bold.
Kevin