Plug-in for Sorting Percentages
Plug-in for Sorting Percentages
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]
[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]
This discussion has been closed.
Replies
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
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!
Regards,
Allan