开发者

How to format numbers in php 1,000 to 1k

开发者 https://www.devze.com 2023-02-05 09:16 出处:网络
Im trying to format the out开发者_Go百科put of numbers in php. I have an amount of posts that show up, and next to each user is the total of posts. But it shows that actual amount, i want it to show i

Im trying to format the out开发者_Go百科put of numbers in php. I have an amount of posts that show up, and next to each user is the total of posts. But it shows that actual amount, i want it to show it in a shorter format, actually, just like they do here at SO with reputation

any ideas?


<?
$numbers = array(100,1000,15141,3421);


function format_number($number) {
    if($number >= 1000) {
       return $number/1000 . "k";   // NB: you will want to round this
    }
    else {
        return $number;
    }
}


foreach($numbers as $number) {
    echo $number . " : " . format_number($number);
    echo "\n";
}


function count_format($n, $point='.', $sep=',') {
    if ($n < 0) {
        return 0;
    }

    if ($n < 10000) {
        return number_format($n, 0, $point, $sep);
    }

    $d = $n < 1000000 ? 1000 : 1000000;

    $f = round($n / $d, 1);

    return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . ($d == 1000 ? 'k' : 'M');
}


Use This Shorten long numbers to K/M/B?

function number_format_short( $n, $precision = 1 ) {
    if ($n < 900) {
        // 0 - 900
        $n_format = number_format($n, $precision);
        $suffix = '';
    } else if ($n < 900000) {
        // 0.9k-850k
        $n_format = number_format($n / 1000, $precision);
        $suffix = 'K';
    } else if ($n < 900000000) {
        // 0.9m-850m
        $n_format = number_format($n / 1000000, $precision);
        $suffix = 'M';
    } else if ($n < 900000000000) {
        // 0.9b-850b
        $n_format = number_format($n / 1000000000, $precision);
        $suffix = 'B';
    } else {
        // 0.9t+
        $n_format = number_format($n / 1000000000000, $precision);
        $suffix = 'T';
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消