如何格式化PHP 1,000到1k的数字

时间:2011-01-16 02:33:35

标签: php wordpress numbers

我试图在php中格式化数字的输出。我有一些帖子显示,每个用户旁边是帖子总数。但是它显示了实际金额,我希望它以更短的格式显示,实际上,就像他们在这里做的那样有声誉

任何想法?

3 个答案:

答案 0 :(得分:13)

<?
$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";
}

答案 1 :(得分:2)

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');
}

答案 2 :(得分:0)

使用此 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';
    }