Angular + Datatables don't sort numbers right

Issue

I got a datatable that shows a numeral connection between 2 Persons. Some of them don’t have any connection, so there might be a String “x” as value for some cells.

The issue I got is the sorting. If I sort by a column, the numbers only get sorted by the first digit, but not the part in front of the dot.

I set the dot as decimal separator like this:

    var lang = {
        "decimal":        ".",
        "emptyTable":     "No data available in table",
        "info":           "Showing _START_ to _END_ of _TOTAL_ entries",
        "infoEmpty":      "Showing 0 to 0 of 0 entries",
        "infoFiltered":   "(filtered from _MAX_ total entries)",
        "infoPostFix":    "",
        "thousands":      "",
        "lengthMenu":     "Show _MENU_ entries",
        "loadingRecords": "Loading...",
        "processing":     "Processing...",
        "search":         "Search:",
        "zeroRecords":    "No matching records found",
        "paginate": {
            "first":      "First",
            "last":       "Last",
            "next":       "Next",
            "previous":   "Previous"
        },
        "aria": {
            "sortAscending":  ": activate to sort column ascending",
            "sortDescending": ": activate to sort column descending"
        }
    };

    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withDOM('frtip')
        .withOption('language', lang)
        .withButtons([
            {
                extend: 'csv',
                text: 'Download as CSV'
            },
            {
                extend: 'excel',
                text: 'Download as XLS'
            }
        ]);

And here is an Excerpt of the data taken from a console output:

datatable

Again a screenshot for explanation of the wrong sorting:

wrong sorting

Here the table is sorted by the column leonard and you can see that this was sorted by the first digit. But instead it should be: 94.36, 66.39, 9.96, 7.31,…

Any Idea what i might got wrong?

Solution

The builtin type detection works great. However, if anything conflicts with a assumed type the column is turned into default alpha sorting. You can have a line of perfect valid dates, but if the last row contain a null or a x as in your case, you end up with alpha sorting. You can solve this by forcing the num datatype in a columnDefs section :

$scope.dtColumnDefs = [
   { targets: 0, type: 'num' } //0 is the column index
];

Dont know your markup, but it would be something like

<table datatable="" dt-options="dtOptions" dt-column-defs="dtColumnDefs">

Now the numbers should be sorted correctl

Answered By – davidkonrad

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.