Tablesorter Decimal Sorting

October 16, 2010

I've had trouble with the jQuery tablesorter not sorting correctly where some of the data contains decimal points. It seems to default back to sorting them as strings.

To get around this problem, I implemented the following new parser, which sorts accurately by converting the numbers to floats first:

$.tablesorter.addParser({ 
  id: 'decimal', 
  is: function(s) { 
    // return false so this parser is not auto detected 
    return false; 
  }, 
  format: function(s) { 
    // format your data for normalization
    var lNumber = parseFloat(s);
    return lNumber;
  }, 
  // set type, either numeric or text 
  type: 'numeric' 
 });

To use, specify the sorter on the header:

$("#gradings").tablesorter({widgets: ['zebra'], sortList: [[3,0],[2,0]]}, headers: {3: {sorter: 'decimal'}});

This sorts by the fourth, then third column. It shows zebra striping. It uses this new decimal parser for the fourth column.