Plug-in for Sorting Percentages

Plug-in for Sorting Percentages

jonathanjonathan Posts: 2Questions: 0Answers: 0
edited May 2010 in General
When creating a datatable with percentages containing the % format symbol at the end, the percentages are not sorted correctly - here's quick plugin based on of Allan's Commas for decimal place plug-in (switched /,/ for /%/ and .decimal point for "") to strip the % symbol and sort the percentages properly. Hopefully this saves someone else a headache.

[code]
jQuery.fn.dataTableExt.oSort['percent-asc'] = function(a,b) {
var x = (a == "-") ? 0 : a.replace( /%/, "" );
var y = (b == "-") ? 0 : b.replace( /%/, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};

jQuery.fn.dataTableExt.oSort['percent-desc'] = function(a,b) {
var x = (a == "-") ? 0 : a.replace( /%/, "" );
var y = (b == "-") ? 0 : b.replace( /%/, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
[/code]

Replies

  • allanallan Posts: 65,430Questions: 1Answers: 10,865 Site admin
    Hi jonathan,

    Very nice - thanks for sharing :-). I've put it up on the sorting plug-ins page now: http://datatables.net/plug-ins/sorting#percentage

    If you'd like the credit altered (name / link) give me a shout.

    Regards,
    Allan
  • tedkalawtedkalaw Posts: 12Questions: 0Answers: 0
    edited August 2011
    Just had an interesting experience with this particular plug-in. I have a lot of blank spaces, as users enter in percentages. In this, "-" is treated equal to 0 (which will sometimes result in 0 and then a bunch of blanks).

    As such, I've been using this instead:

    [code]
    jQuery.fn.dataTableExt.oSort['percent-asc'] = function(a,b) {
    var x = (a == "-") ? 0 : a.replace( /%/, "" );
    var y = (b == "-") ? 0 : b.replace( /%/, "" );
    x = parseFloat( x );
    y = parseFloat( y );
    if(isNaN(x)){
    if(isNaN(y))
    return 0;
    else
    return 1;
    }
    else if (isNaN(y))
    return -1;

    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['percent-desc'] = function(a,b) {
    var x = (a == "-") ? 0 : a.replace( /%/, "" );
    var y = (b == "-") ? 0 : b.replace( /%/, "" );
    x = parseFloat( x );
    y = parseFloat( y );
    if(isNaN(x)){
    if(isNaN(y))
    return 0;
    else
    return 1;
    }
    else if (isNaN(y))
    return -1;

    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    };
    [/code]

    Hope it helps someone else out!
  • allanallan Posts: 65,430Questions: 1Answers: 10,865 Site admin
    Looks like a good modification - thanks for sharing it with us!

    Regards,
    Allan
This discussion has been closed.