Number sorting fail

Number sorting fail

jkd77jkd77 Posts: 3Questions: 0Answers: 0
edited August 2011 in DataTables 1.8
Please see the following example page: http://lovefunding.werremeyer.com/loan-closings/

Note that when sorting the 'loan amount' column that the largest number, $10,512,700 seems to not sort properly.

Thoughts? Thanks!

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    it will sort by string unless you tell it otherwise.

    [code]
    // add a "currency" sorting class
    jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
    /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
    var x = a == "-" ? 0 : a.replace( /,/g, "" );
    var y = b == "-" ? 0 : b.replace( /,/g, "" );

    /* Remove the currency sign */
    x = x.substring( 1 );
    y = y.substring( 1 );

    /* Parse and return */
    x = parseFloat( x );
    y = parseFloat( y );
    return x - y;
    };

    jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
    /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
    var x = a == "-" ? 0 : a.replace( /,/g, "" );
    var y = b == "-" ? 0 : b.replace( /,/g, "" );

    /* Remove the currency sign */
    x = x.substring( 1 );
    y = y.substring( 1 );

    /* Parse and return */
    x = parseFloat( x );
    y = parseFloat( y );
    return y - x;
    };



    jQuery(document).ready(function($)
    {
    $('.loanClosings').dataTable({
    "bFilter": false
    aoColumnDefs: [ { aTargets: [3], sType: "currency" } ] // use the "currency" sorting class added above, apply to column 3
    });
    });
    [/code]
  • jkd77jkd77 Posts: 3Questions: 0Answers: 0
    Awesome! Thanks!
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    a little more info: if sType is not specified, data tables will try to detect the right data type to apply sorting. basic data types included in datatables by default are numbers, strings, etc. you can add more data types and sort routines as we did above. (the currency values will detect as strings unless you add a custom type detector routine. )

    the code above overrides sort detection and specifies the type to use with sType. it also adds sort functions for that type.

    you can find more info and sort plug in types/routines at http://www.datatables.net/plug-ins/sorting
This discussion has been closed.