Percentage sorting

Percentage sorting

brendobrendo Posts: 1Questions: 0Answers: 0
edited September 2011 in DataTables 1.8
I have a column in my datatable for percentage. The column values are displayed like 100%. When sorting by this column, it treats it as a string because the order is like: 0%, 100%, 20%, 3% instead of being 0%, 3%, 20%, 100%

Any ideas?

Replies

  • jp_noronhajp_noronha Posts: 59Questions: 0Answers: 0
    edited September 2011
    try this. just check if you use comma or point as decimal separator


    [code]
    /*=============================================================================
    Percent
    ============================================================================= */
    jQuery.fn.dataTableExt.oSort['percent-asc'] = function(a, b)
    {
    var x = a == "-" ? 0 : a.replace(/\./g, "");
    var y = b == "-" ? 0 : b.replace(/\./g, "");
    x = x.replace(/,/, ".");
    y = y.replace(/,/, ".");
    x = x.replace(/%/, "");
    y = y.replace(/%/, "");

    x = parseFloat(x);
    y = parseFloat(y);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['percent-desc'] = function(a, b)
    {
    var x = a == "-" ? 0 : a.replace(/\./g, "");
    var y = b == "-" ? 0 : b.replace(/\./g, "");
    x = x.replace(/,/, ".");
    y = y.replace(/,/, ".");
    x = x.replace(/%/, "");
    y = y.replace(/%/, "");

    x = parseFloat(x);
    y = parseFloat(y);
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    };
    jQuery.fn.dataTableExt.aTypes.unshift(
    function(sData)
    {
    var sValidChars = "0123456789.-,";
    var Char;

    /* Check the numeric part */
    for (i = 0; i < sData.length - 1; i++)
    {
    Char = sData.charAt(i);
    if (sValidChars.indexOf(Char) == -1)
    {
    return null;
    }
    }

    /* Check sufix % */
    if (sData.charAt(sData.length - 1) == "%")
    {
    return 'percent';
    }
    return null;
    }
    );
    [/code]
  • allanallan Posts: 63,368Questions: 1Answers: 10,449 Site admin
    This example will also be of use for how to use this sorting plug-in: http://datatables.net/release-datatables/examples/plug-ins/sorting_sType.html

    Allan
This discussion has been closed.