javascripthtmldatatables-1.10

Datatables how do I sort this table correctly?


My datatable is not sorting correctly. I think the problem is related to the decimal values as there is no consistency in them. What is the best way to sort this correctly? Do I need a special plugin for this? Any help/advice appreciated. Thanks in advance. Please see code below. Thank you very much for your time and assistance.

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

  } );
<!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>
<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>


Solution

  • DataTables default is to sort as text. If you want to sort numerically, you need to specify that in your columnDefs.

    You can set your column type as a num, as described here: https://datatables.net/reference/option/columns.type

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