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

2019-07-17 19:48发布

Im trying to format the output 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?

3条回答
混吃等死
2楼-- · 2019-07-17 20:02
<?
$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";
}
查看更多
Evening l夕情丶
3楼-- · 2019-07-17 20:16
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');
}
查看更多
ゆ 、 Hurt°
4楼-- · 2019-07-17 20:25

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';
    }
查看更多
登录 后发表回答