Search code examples
sortingag-gridag-grid-angular

ag-grid row sorting does not work with decimals and empty values


I am using ag-grid with version 20.2.0

Column contains positive or negative decimal values such as -0.000023 or 0.000000056387 or simply blanks.

I have applied sortable: true for this column

When sorting is triggered the sorted order looks something like this:

0.0205
0.00883
-0.00893
0.0142
0.000239
-0.0135
0.0345
<blank>
0.00456
-0.355
-0.00166

My expectation is that all the non blank numbers should be sorted correctly and and all blanks should go at the end.

I have tried to add valueFormatter in column definition as:

{
headerName: field_name,
sortabke: true,
field: field_name,
valueFormatter: format_numbers
}

function format_numbers(val) {
if(val.value === 'NaN') {
return '';
}
else {
return Number(val.value).toPercision(3);
}

Solution

  • Please could you provide a plunker to demonstrate?

    The valueFormatter is for formatting the values displayed to the user. You need a comparator function to change the way rows are sorted

    https://www.ag-grid.com/angular-grid/row-sorting/#example-custom-sorting

    {
    headerName: field_name,
    sortable: true,
    field: field_name,
    comparator: myComparator
    }
    
    function myComparator(value1, value2) {
      if (value1 === null && value2 === null) {
        return 0;
      }
      if (value1 === null) {
        return -1;
      }
      if (value2 === null) {
        return 1;
      }
      return value1 - value2;
    }
    

    Disclaimer, I've just copied that from the ag-grid website in case the link fails in the future. No guarantee there are no typos!