Search code examples
jqueryhtml-tabletablesorter

sorting integers and percentage values both in single column using jquery table sorter


I am facing issue with table sorter i have a column with both integers and percentage values so after applying the sorting the column is getting sorted by considering integer values.

For Example,If i have the values like 4.19, which is more than 4.48%, but 4.48% is first even though the percentage (4.48%) is less than 4.19.

Can anyone help me out this.


Solution

  • To convert a percentage into a fraction, you'll need to add a custom parser (demo):

    $(function () {
    
        $.tablesorter.addParser({
            id: "calc-percent",
            is: function(s) {
                return false;
            },
            format: function(s, table) {
                var v =  s ? $.tablesorter.formatFloat(s.replace(/%/g, ""), table)/100 : s;
                return /%/.test(s) ? v/100 : v;
            },
            type: "numeric"
        });
    
        $('table').tablesorter({
            theme: 'blue',
            headers: {
                1: { sorter: "calc-percent" }
            },
            widgets: ['zebra', 'columns']
        });
    });