使用datatables.js对格式为#,###,###.##的数字进行排序

 zhanghao320829 发布于 2023-02-13 13:10

在我的国家,表达数字的惯例是使用.作为千位分隔符和小数分隔符.一个例子是:25.367,212我无法使datatables.js对使用此格式的任何列进行排序.

我使用以下扩展名:

//formatted number sort
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "formatted-num-pre": function (a) {
    a = (a === "-" || a === "") ? 0 : a.replace(/[^\d\-\.]/g, "");
    return parseFloat(a);
  },

  "formatted-num-asc": function (a, b) {
    return a - b;
  },

  "formatted-num-desc": function (a, b) {
    return b - a;
  }
});

//formatted number autodetection
jQuery.fn.dataTableExt.aTypes.unshift(
    function (sData) {
      var deformatted = sData.replace(/[^\d\-\.\/a-zA-Z]/g, '');
      if ($.isNumeric(deformatted) || deformatted === "-") {
        return 'formatted-num';
      }
      return null;
    }
);

我搜索了数据表文档和论坛,但没有找到解决方案.有什么建议?我使用的是jquery 1.9.1和datatables 1.9.4

1 个回答
  • 我最终通过以下方式解决了这个问题:

    jQuery.fn.dataTableExt.oSort['numeric-comma-asc'] = function (a, b) {
        //remove the dots (.) from the string and then replaces the comma with a dot
      var x = (a == "-") ? 0 : a.replace(/\./g, "").replace(/,/, ".");
      var y = (b == "-") ? 0 : b.replace(/\./g, "").replace(/,/, ".");
      x = parseFloat(x);
      y = parseFloat(y);
      return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    };
    
    jQuery.fn.dataTableExt.oSort['numeric-comma-desc'] = function (a, b) {
      var x = (a == "-") ? 0 : a.replace(/\./g, "").replace(/,/, ".");
      var y = (b == "-") ? 0 : b.replace(/\./g, "").replace(/,/, ".");
      x = parseFloat(x);
      y = parseFloat(y);
      return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    };
    
    //numeric comma autodetect
    jQuery.fn.dataTableExt.aTypes.unshift(
                function (sData) {
       //include the dot in the sValidChars string (don't place it in the last position)
                  var sValidChars = "0123456789-.,";
                  var Char;
                  var bDecimal = false;
    
                  /* Check the numeric part */
                  for (i = 0 ; i < sData.length ; i++) {
                    Char = sData.charAt(i);
                    if (sValidChars.indexOf(Char) == -1) {
                      return null;
                    }
    
                    /* Only allowed one decimal place... */
                    if (Char == ",") {
                      if (bDecimal) {
                        return null;
                      }
                      bDecimal = true;
                    }
                  }
    
                  return 'numeric-comma';
                }
            );
    

    2023-02-13 13:12 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有