2012-11-23 37 views
-1

我有塊顯示twitter句柄的以下數字。很棒。唯一的問題是,有11,000多個追隨者,並且API不會輸入逗號。我將如何合併JavaScript來格式化數字,使其看起來不錯?格式化來自Twitter API的數據

下面是我使用Twitter的代碼:

$(function(){ 
$.ajax({ 
    url: 'http://api.twitter.com/1/users/show.json', 
    data: {screen_name: 'handle'}, 
    dataType: 'jsonp', 
    success: function(data) { 
     $('#followers').html(data.followers_count); 
    } 
}); 
}); 


感謝neiker與解決方案幫助!

function numberWithCommas(x) { 
     return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
    } 

    $.ajax({ 
     url: 'http://api.twitter.com/1/users/show.json', 
     data: {screen_name: 'handle'}, 
     dataType: 'jsonp', 
     success: function(data) { 
      $('#followers').html(numberWithCommas(data.followers_count)); 
     } 
    }); 
+0

檢查:http://stackoverflow.com/questions/2901102/how-to-print-number-with-commas-as-thousands-separators-in-javascript – neiker

+0

呀看到一個幾天前,試圖實現,但我不知道JavaScript足以讓它工作。 – cfox

+1

將「numberWithCommas」聲明放在ajax調用之上。然後,更改:$('#followers')。html(data.followers_count);到這個$('#followers')。html(numberWithCommas(data.followers_count)); – neiker

回答

0
function numberWithCommas(x) { 
     return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
    } 

    $.ajax({ 
     url: 'http://api.twitter.com/1/users/show.json', 
     data: {screen_name: 'handle'}, 
     dataType: 'jsonp', 
     success: function(data) { 
      $('#followers').html(numberWithCommas(data.followers_count)); 
     } 
    });