我的数据表网格中有一列表示货币值,我如何正确排序这些值,因为数据表只按第一个数字排序,例如:
9.000,00
8.000,00
5.454.043,00
4.454.043,00
当然应该是这样的:
5.454.043,00
4.454.043,00
9.000,00
8.000,00
我正在使用number_format
设置我的货币格式。
php:
<td>".number_format($money,2,',','.')."</td>
有什么问题,请客气。
谢谢。
编辑:
正如@Mikhail的回答,试试这个,但第3位的列不再排序。
...
"aoColumnDefs": [
{ "sType": "numeric", "aTargets": [ 3 ] }
],
...
编辑2
多一点代码:
php:
while(!$res->EOF){
... // post only the 3 <td> position
<td style='text-align: right;'>".number_format($value,2,',','.')."</td>
...
$res->MoveNext();
}
js数据表
var oTable = $('#example').dataTable({
"bJQueryUI": true,
"sScrollY": "225px",
"sScrollX": "100%",
"sScrollXInner": "100%",
"bDestroy" : true,
"bScrollCollapse": true,
"aoColumnDefs": [
{ "sType": "numeric", "aTargets": [ 3 ] }
],
"sDom": '<"H"Tfr>t<"F"ip>',
"oTableTools": {
"sSwfPath": "js/DataTables/extras/TableTools/media/swf/copy_cvs_xls_pdf.swf",
"sRowSelect": "single",
"aButtons": [
{
"sExtends": "xls",
"sButtonText": "Excel"
},
{
"sExtends": "print",
"sButtonText": "Print"
}
]
},
"aaSorting": [[ 0, "asc" ]],
"bPaginate": false
});
解决方案
我的解决方案是创建一个没有number_format
的值的新列,像this一样隐藏它们。通过搜索其他排序方式,我找到了iDataSort现在我可以在我的显示栏中设置任何内容的格式。
您需要将字符串转换回float,您可以为此定义自己的数据类型(未经测试):
(function(){
var tofloat = function(n) {
return parseFloat(n.replace('.', '').replace(',', '.'));
};
$.fn.dataTableExt.oSort['mynumeric-asc'] = function(a, b) {
a = tofloat(a);
b = tofloat(b)
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
};
$.fn.dataTableExt.oSort['mynumeric-desc'] = function(a, b) {
a = tofloat(a);
b = tofloat(b)
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
};
}());
则声明"sType": "mynumeric"
相比之下,这是DataTables中数字排序的全部代码:
/*
* numerical sorting
*/
"numeric-asc": function ( a, b )
{
var x = (a=="-" || a==="") ? 0 : a*1;
var y = (b=="-" || b==="") ? 0 : b*1;
return x - y;
},
"numeric-desc": function ( a, b )
{
var x = (a=="-" || a==="") ? 0 : a*1;
var y = (b=="-" || b==="") ? 0 : b*1;
return y - x;
}
如您所见,转换为数字是通过将字符串乘以1来实现的,1不知道逗号或用作小数分隔符的点。
简而言之,您可以使用:
natsort($array);
您需要指定列为"numeric"。
http://datatables.net/usage/columns#sType
祝你好运!
在看不到更多代码的情况下,很难确定具体要做什么,但它之所以能像现在这样执行,似乎是由于number_format
函数。这将返回一个string
,因此排序是正确的。在将其转换为字符串之前,您需要执行排序。但要获得更深入的解释,您需要提供更多深入的代码。