jQuery Tablesorter and Decimals

March 15, 2010

I had a situation where I needed the tablesorter plugin to work with decimal numbers, where the first number was (probably) static, and the second increased. The ordering I needed was 17.1->17.9, then 17.10->17.20 etc.

Here's the javascript to use this for the sorting on the first column of my table:

$(document).ready(function(){
  $.tablesorter.addParser({ 
    // set a unique id 
    id: 'versions', 
    is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
    }, 
    format: function(s) { 
      // format your data for normalization 
      var lVersionsArray = s.split('.');
      var lPower = 3;
      var lPosition = 0;
      var lTotal = 0;
      while (lPosition < lVersionsArray.length)
      {
        var lFactor = Math.pow(10000, lPower);
        var lValue = lVersionsArray[lPosition] * lFactor;
        lTotal = lTotal + lValue;
        lPower = lPower - 1;
        lPosition = lPosition + 1;
      }
      return lTotal;
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
  }); 
  $("#versions").tablesorter({widgets: ['zebra'], headers: { 0: { sorter:'versions'}}});
});

Tags: jquery tablesorter