Search code examples
javascriptjquerytablesorter

Tablesorter, sort simple number


i try to sort simple number like :

11 256 232
256 236
23 056
11 536
1 023 585

with tablesorter plugin.

But no one of my test is ok.

i try :

$.tablesorter.addParser({
  id: 'colpap',
  is: function (s) {
    return false;
  },
  format: function (s) {
    return s.replace(/\s+/g, '');
  },
  type: 'numeric'
});

Do you have an idea ?


Solution

  • When you set a "numeric" type for the parser, the sorter is set to evaluate number values, not strings.

    So what you need to do is parse the number and return that value

    $.tablesorter.addParser({
      id: 'colpap',
      is: function (s) {
        return false;
      },
      format: function (s) {
        var number = parseFloat(s.replace(/\s+/g, ''));
        return isNaN(number) ? s : number;
      },
      type: 'numeric'
    });
    

    * Note: the above parser will not work if your numbers are in European format where commas are used in place of a decimal, e.g. 1 234 545,34.

    I don't know what version of tablesorter you're using, so I'm going to assume it's the original - here is a demo.