【问题标题】:DataTables sort currencyDataTables 对货币进行排序
【发布时间】:2013-09-06 12:38:43
【问题描述】:

请提供实时示例,如何以“34 566.00 ek”格式对货币进行排序。在 DataTables 脚本中。

这里是 JSFiddle 示例:http://jsfiddle.net/HEDvf/643/

$('#example').dataTable({
   "aoColumns": [
    null,
   ],        
  "aaSorting": [[ 0, "desc" ]],
  "bStateSave": false,
  "iDisplayLength": 50,
});

【问题讨论】:

    标签: sorting format datatables currency


    【解决方案1】:

    查看非常广泛的数据表文档。在那里,您将找到几乎所有数据表问题的简单解决方案。例如,有一些小插件功能可以添加对货币列的排序支持。

    一个基于你得到的例子:

    // 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,
    });
    

    文档链接:

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

    Datatables 还能够自动检测列类型,但它会因为所有不同的格式而变得有点复杂。类型检测:http://datatables.net/plug-ins/type-detection#currency

    【讨论】:

    【解决方案2】:

    我没有足够的声誉在@Gigo 的答案中添加命令。所以我会发布这个作为答案。

    如果您使用欧洲货币格式,点 '.'用作千位分隔符而不是逗号“,”。所以排序脚本将无法正常工作,因为 1.000,00 被解释为 ONE point ZERO

    要解决此问题,请将正则表达式更改为:

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

    点改为逗号,现在 1.000,00 将被解释为千分零。

    【讨论】:

    • 好点。如果列中的所有数字的格式都相同,我猜这不会有任何影响,但是无论如何都应该调整正则表达式以匹配格式。
    【解决方案3】:

    可能是一个肮脏的解决方案,但您也可以使用它从字符串中删除数字格式 (,)

    jQuery.extend(jQuery.fn.dataTableExt.oSort, {
        "currency-pre": function (a) {
            console.log("PRE "+a);
            
            a = (a === "-") ? 0 : a.split(',').join('').replace(/[^\d\-\.]/g, "");
            return parseFloat(a);
        },
        "currency-asc": function (a, b) {
            console.log("ASC "+a);
            return a - b;
        },
        "currency-desc": function (a, b) {
            console.log("DESC "+a);
            return b - a;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 2016-01-07
      • 2020-10-20
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多