格式化数字10000如10k

时间:2013-01-15 00:48:10

标签: javascript jquery

我有一个5位数字,比如10000,我希望将其显示为10k,因为我最终会有6位数字(我实际上是在谈论Twitter计数) 。我想我必须要子串,但我还不习惯JavaScript。

这就是我正在尝试使用的内容。它基本上得到了JSON的追随者数量。

<script type="text/javascript">
    $(function() {
        $.ajax({
            url: 'http://api.twitter.com/1/users/show.json',
            data: {
                screen_name: 'lolsomuchcom'
            },
            dataType: 'jsonp',
            success: function(data) {
            $('#followers').html(data.followers_count);
                }
        });
    });
</script>

2 个答案:

答案 0 :(得分:3)

尝试:

$('#followers').html(Math.floor(data.followers_count/1000) + 'K');

答案 1 :(得分:2)

$('#followers').html(data.followers_count.substring(0, data.followers_count.length - 3)); 

演示:http://jsfiddle.net/ZWfPW/

编辑..这里是文字代码,仅供您使用:

$(function() {
    $.ajax({
        url: 'http://api.twitter.com/1/users/show.json',
        data: {
            screen_name: 'lolsomuchcom'
        },
        dataType: 'jsonp',
        success: function(data) {
            // Ensure it's a string
            data.followers_count += '';
            $('#followers').html(data.followers_count.substring(0, data.followers_count.length - 3) + 'K');
        }
    });
});