Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables sort currency

Please help with live example, how to sort currency in format "34 566.00 ek." in DataTables script.

Here is JSFiddle example: http://jsfiddle.net/HEDvf/643/

$('#example').dataTable({
   "aoColumns": [
    null,
   ],        
  "aaSorting": [[ 0, "desc" ]],
  "bStateSave": false,
  "iDisplayLength": 50,
});
like image 366
user2481034 Avatar asked Dec 07 '22 05:12

user2481034


2 Answers

Have a look at the very extensive datatables documentation. There you will find simple solutions to almost all problems you will ever have with datatables. There are for example little plugin functions to add sorting support for currency columns.

An example based on what you got:

// add sorting methods for currency columns
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "currency-pre": function (a) {
        a = (a === "-") ? 0 : a.replace(/[^\d\-\.]/g, "");
        return parseFloat(a);
    },
    "currency-asc": function (a, b) {
        return a - b;
    },
    "currency-desc": function (a, b) {
        return b - a;
    }
});

// initialize datatable and explicitly set the column type to "currency"
$('#example').dataTable({
    "aoColumns": [{"sType": "currency"}],
    "aaSorting": [[0, "desc"]],
    "bStateSave": false,
    "iDisplayLength": 50,
});

Links to the documentation:

Sorting: http://datatables.net/plug-ins/sorting#currency

Datatables is also able to automatically detect column types, but it gets a bit complicated with all the different formattings. Type-detection: http://datatables.net/plug-ins/type-detection#currency

like image 179
Gigo Avatar answered Dec 22 '22 14:12

Gigo


I have no reputation enough to add a command to the answer of @Gigo. So I will post this as a answer.

If you use European currency format, a point '.' is used as thousand separator instead of a comma ','. So the sorting script won't work correctly because 1.000,00 is interpreted as ONE point ZERO

To get this fixed, change the regex to:

/[^\d\-\,]/g

Point changed to comma, now 1.000,00 will be interpreted as ONE THOUSAND point ZERO.

like image 38
Timo002 Avatar answered Dec 22 '22 14:12

Timo002