2016-11-29 25 views
-1

用下面的jQuery代碼訂貨錶行,數字與點的數千名格式不正確排序:jQuery的不能爲了成千上萬號點號分隔訂購

這些數字:

1.000, 2.500,4.000,850

被排序爲:

850,4.000,2.500 ,1.000

我需要訂購這些樣品號碼而不刪除點。

jQuery代碼:

$('th').each(function (column) { 
    $(this).addClass('sortable').click(function() { 
     var findSortKey = function ($cell) { 
      return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase(); 

     }; 
     var sortDirection = $(this).is('.sorted-asc') ? -1 : 1; 
     var $rows = $(this).parent().parent().parent().find('tbody tr').get(); 
     var bob = 0; 
     // Loop through all records and find 
     $.each($rows, function (index, row) { 
      row.sortKey = findSortKey($(row).children('td').eq(column)); 
     }); 

     // Compare and sort the rows alphabetically or numerically 
     $rows.sort(function (a, b) { 
      if (a.sortKey.indexOf('-') == -1 && (!isNaN(a.sortKey) && !isNaN(a.sortKey))) { 
       // Rough Numeracy check 

        if (parseInt(a.sortKey) < parseInt(b.sortKey)) { 
         return -sortDirection; 
        } 
        if (parseInt(a.sortKey) > parseInt(b.sortKey)) { 
         return sortDirection; 
        } 

      } else { 
       if (a.sortKey < b.sortKey) { 
        return -sortDirection; 
       } 
       if (a.sortKey > b.sortKey) { 
        return sortDirection; 
       } 
      } 
      return 0; 
     }); 

     // Add the rows in the correct order to the bottom of the table 
     $.each($rows, function (index, row) { 
      $('tbody').append(row); 
      row.sortKey = null; 
     }); 

     // Identify the column sort order 
     $('th').removeClass('sorted-asc sorted-desc'); 
     var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')'); 
     sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc'); 

     // Identify the column to be sorted by 
     $('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted'); 
    }); 
}); 
+3

Th這就是爲什麼你***從未***格式化或本地化的日期,數字等排序 – connexo

+0

顯然'1.000'小於'850'。 –

+0

@PraveenKumar您標記爲重複的問題與DataTables有關。這是一個自定義函數,而不是插件。該解決方案不符合我的要求。 – user3472675

回答

0

於JavaScript有沒有分隔符千數。只爲小數,它是.

隨着你不能確定你的電話號碼變量Intfloat,因爲這將被視爲十進制數,它小數點後取出零點分隔。

您仍然可以用圓點對您的號碼進行排序。

  • 由空值( 「」)
  • 排序你的數字
  • 更換點並添加點分隔的字符串

請嘗試:

var numbers = ["4.500", "1.000", "1", "5", "25", "10"]; 
 
var num = []; 
 

 
$.each(numbers,function(i,e){ 
 
    dotPos = numbers[i].replace(/\./g,"") 
 
    num.push(parseInt(dotPos)) 
 
}) 
 
num.sort(function(a, b){return a-b}); 
 
$.each(num,function(i,e){ 
 
    console.log(num[i].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>