Dhanuka777
Dhanuka777

Reputation: 8636

Jquery Datatables how to sort a custom formatted numeric column?

I have a column in a data table which renders numeric values as formatted currency values e.g "$5,66666.77 USD". Here is the part of the Jquery table definition for this column,

            data: "amount",
            orderable: true,
            searchable: false,
            render: (data, type, row) => {
                var formattedAmount = "$" + data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + " " + "USD";
                return formattedAmount;
            }

When I don't have the "USD" suffix it gets sorted correctly. But when I have USD it sorts like a string. Is there a work around for this? Can I define a different value for sort data?

I am using this the Typescript typings.

"data" attribute accepts ObjectColumnData, I tried to use this but it's not using the sort field I define.

 interface ObjectColumnData {
        _: string;
        filter?: string;
        display?: string;
        type?: string;
        sort?: string;
    }

Do I have to write a custom sort for this?

Upvotes: 2

Views: 660

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58900

You can return formatted value only when data would be displayed, otherwise you can return unformatted value for sorting, filtering or type detection.

For example, in JavaScript:

render: function(data, type, row){
    if(type === 'display'){
        data = "$" + data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + " " + "USD"; 
    }

    return data;
}

Upvotes: 6

Related Questions