tablesorter icon indicating copy to clipboard operation
tablesorter copied to clipboard

Comma seperated numbers

Open shanejones opened this issue 8 years ago • 5 comments

I have an issue where comma separated numbers aren't sorting the same as non comma separated numbers.

Doing a Low to High sort results in the following

  • 0
  • 1,223
  • 10,000
  • 12
  • 123

shanejones avatar Dec 11 '16 16:12 shanejones

There is a workaround for this

    $(function () {
        $.tablesorter.defaults.groupSeparator = ",";
        $.tablesorter.formatFloat = function (s) {
            var regexp = new RegExp("[" + this.defaults.groupSeparator + "]","g")
            var i = parseFloat(s.replace(regexp, ''));
            return (isNaN(i)) ? 0 : i;
        };
        $("#myTable").tablesorter();
    });

juanalvarezg avatar Jan 04 '17 17:01 juanalvarezg

does not work for me

nekromoff avatar Jan 09 '17 17:01 nekromoff

You'd need to add a custom parser (demo):

var unitSeparator = ',';

var regex = new RegExp('[\s' + unitSeparator + ']', 'g');

$.tablesorter.addParser({
  id: 'removeDigitSep',
  is: function() {
    // don't autodetect
    return false;
  },
  format: function(s) {
    var num = $.tablesorter.formatFloat(s.replace(regex, ''));
    // return numeric value or original string
    return $.isNumeric(num) ? num : s;
  }
});

$('table').tablesorter({
  headers: {
    0: {
      sorter: 'removeDigitSep'
    }
  }
});

Mottie avatar Jul 17 '17 17:07 Mottie

Replying to @juanalvarezg This worked in terms of sorting correctly, but now I can only sort once. On my first click, it sorts in descending order. On my second click, the table "flashes" very briefly but the display not change.

There is a workaround for this

$(function () {
        $.tablesorter.defaults.groupSeparator = ",";
        $.tablesorter.formatFloat = function (s) {
            var regexp = new RegExp("[" + this.defaults.groupSeparator + "]","g")
            var i = parseFloat(s.replace(regexp, ''));
            return (isNaN(i)) ? 0 : i;
        };
        $("#myTable").tablesorter();
    });

rafic20 avatar Dec 20 '17 16:12 rafic20

I dont know why :( this workaround just makes sure that we parse a float number. the sorting happens outside this logic. I did that on january 2017. Are you using the latest component? if so, maybe try with the version that was released around january 2017. good luck!

juanalvarezg avatar Dec 20 '17 18:12 juanalvarezg