You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确对Datatables中混合小数与整数的列进行排序?

DataTables 数字列正确排序方案

问题原因

你当前使用的natural排序类型是针对字符串的自然排序逻辑,不适合整数+小数混合的纯数字排序需求,这才导致排序异常。

解决步骤

  • 替换排序类型:把columnDefs里的type: 'natural'改成type: 'numeric',这是DataTables原生支持的数字专用排序类型,能自动识别整数、小数并按数值大小排序。
  • 清理单元格多余空格:确保<td>内的数字前后没有多余空格(虽然numeric类型会自动忽略,但清理后能避免意外问题)。

修改后的代码

JavaScript 代码

$(document).ready(function() {
  $('#abc').DataTable({
    columnDefs: [
      { type: 'numeric', targets: 0 }
    ],
    responsive: true,
    bSort: true,   
    order: []
  });
});

HTML 代码

<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
    <meta charset=utf-8 />
    <title>DataTables - JS Bin</title>
  </head>
<body>
<table id="abc" style="width: 100%;">
  <thead>
    <tr>
      <th style="width: 25%;">abcd</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>1.2</td></tr>
    <tr><td>3.001</td></tr>
    <tr><td>8.1025</td></tr>
    <tr><td>40</td></tr>
    <tr><td>41</td></tr>
    <tr><td>180</td></tr>
    <tr><td>205</td></tr>
  </tbody>
</table>
</body>
</html>

额外说明

不需要安装任何特殊插件,原生DataTables的numeric排序类型完全能处理这种整数、小数混合的排序场景。如果后续遇到带千分位、货币符号等复杂格式的数字,再考虑使用num-fmt类型或自定义排序插件即可。

内容的提问来源于stack exchange,提问作者newuser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:52:05