Question regarding the sum but for floats

Question regarding the sum but for floats

BartTechneBartTechne Posts: 24Questions: 6Answers: 0

! "footerCallback": function ( row, data, start, end, display ) {
! var api = this.api(), data;
!
! // Remove the formatting to get integer data for summation
! var intVal = function ( i ) {
! return typeof i === 'string' ?
! i.replace(/[\$,]/g, '')*1 :
! typeof i === 'number' ?
! i : 0;
! };
! // Total over all pages
! total = api
! .column( 5 )
! .data()
! .reduce( function (a, b) {
! return intVal(a) + intVal(b);
! }, 0 );
! // Total over this page
! pageTotal = api
! .column( 5, { page: 'current'} )
! .data()
! .reduce( function (a, b) {
! return intVal(a) + intVal(b);
! }, 0 );
!
! // Update footer
! $( api.column( 5 ).footer() ).html(
! '$'+pageTotal +' ( $'+ total +' total)'
! );
! }

When i alert Total for example i get the message NaN
In the colums the values are floats
Im not that experienced with JS :(

This question has an accepted answers - jump to answer

Answers

  • rf1234rf1234 Posts: 2,990Questions: 87Answers: 421
    Answer ✓

    I think the values in the column are not floats but strings. That what they usually are. So you would need to convert them into the right format and then parse them as floats.

    Here I have a field "rowTotal" coming from a data table. Depending on the user language it can look like 100,000.00 (English) or 100.000,00 (German).

    So first I convert it to this format 100000.00
    This format can be converted to float because Javascript recognizes it as a numer. Javascript does not recognize this as a number: 100000,00

    This is the example:

    var sum = 0;
    
    if (lang == 'de') { //German formatting
        rowTotal = rowTotal.toString().replace( /[\.]/g, "" );
        rowTotal = rowTotal.toString().replace( /[\,]/g, "." );            
    } else { //English formatting
        rowTotal = rowTotal.toString().replace( /[\,]/g, "" );
    }
    
    if ( ! isNaN( parseFloat(rowTotal) ) ) {   
        sum += parseFloat(rowTotal);
    }
    
This discussion has been closed.