tablesorter
tablesorter copied to clipboard
Comma seperated numbers
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
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();
});
does not work for me
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'
}
}
});
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();
});
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!