Search code examples
javascriptjquerytablesorter

JQUERY Tablesorter not sorting numeric columns correctly


I'm having problems sorting columns that contain floating point numbers and integers:

Example

Column currently being sorted like so :

4697.2
403.95
399.38
317.94
316.44
3138.7
308.28
262.75
1839.5
179.94
159.97
145.99
103.95
94.95
90.24
819.9

I would like to sort the column by value as it appears to be sorting the figures by character length at the moment - possibly?

Here's my javascript :

<script>

$(function(){
    $('table').tablesorter({
        widgets        : ['zebra', 'columns', 'stickyHeaders'],
        usNumberFormat : false,
        numberSorter: function (a, b, direction) {
    if (a >= 0 && b >= 0) { return direction ? a - b : b - a; }
    if (a >= 0) { return -1; }
    if (b >= 0) { return 1; }
    return direction ? b - a : a - b;
}
    });
});

</script>

Could somebody please let me know what I need to do to correct this? Thanks


Solution

  • The fix was suggested by @fuchs777. The usNumberFormat setting was set to false. Which meant the tablesorter was treating the values as if they were in German number format, e.g. 1.234.567,89. With German number format the thousands are denoted by periods (full stops) and not commas.

    The fix was setting usNumberFormat : true

    For example:

    $(function(){
        $('table').tablesorter({
            widgets        : ['zebra', 'columns', 'stickyHeaders'],
            usNumberFormat : true,
            numberSorter: function (a, b, direction) {
            if (a >= 0 && b >= 0) { return direction ? a - b : b - a; }
            if (a >= 0) { return -1; }
            if (b >= 0) { return 1; }
            return direction ? b - a : a - b;
        }
        });
    });