PHP 计数四舍五入到 K 样式计数像 facebook 共享 . . .推特按钮等

php
2022-08-30 15:26:40

好吧,所以我正试图将我的点击计数器四舍五入数千个数字,例如3K,也可以显示3000次点击,例如Facebook Share和Twitter Tweet Buttons。这是我的代码。你知道我做错了什么吗?

$postresultscount = (($resultscount) ? $resultscount->sumCount : 1);
$k = 1000;
$L = '';
if ($postresultscount > $k) {
    $echoxcount = round($postresultscount/$k);
    $L = 'K';
} else if ($postresultscount == $k) {
    $echoxcount = 1;
    $L = 'K';
} else {
    $echoxcount = $postresultscount;
}

echo 'document.write("'.$echoxcount.' '.$L.'")';

答案 1

这里有一个函数,可以将数字格式化为最接近的千,例如千克,百万,十亿和万亿,并用逗号PHP

功能

function thousandsCurrencyFormat($num) {

  if($num>1000) {

        $x = round($num);
        $x_number_format = number_format($x);
        $x_array = explode(',', $x_number_format);
        $x_parts = array('k', 'm', 'b', 't');
        $x_count_parts = count($x_array) - 1;
        $x_display = $x;
        $x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '');
        $x_display .= $x_parts[$x_count_parts - 1];

        return $x_display;

  }

  return $num;
}

输出

thousandsCurrencyFormat(3000) - 3k
thousandsCurrencyFormat(35500) - 35.5k
thousandsCurrencyFormat(905000) - 905k
thousandsCurrencyFormat(5500000) - 5.5m
thousandsCurrencyFormat(88800000) - 88.8m
thousandsCurrencyFormat(745000000) - 745m
thousandsCurrencyFormat(2000000000) - 2b
thousandsCurrencyFormat(22200000000) - 22.2b
thousandsCurrencyFormat(1000000000000) - 1t (1 trillion)

资源

https://code.recuweb.com/2018/php-format-numbers-to-nearest-thousands/


答案 2
function shortNumber($num) 
{
    $units = ['', 'K', 'M', 'B', 'T'];
    for ($i = 0; $num >= 1000; $i++) {
        $num /= 1000;
    }
    return round($num, 1) . $units[$i];
}

我从一个函数中改编了这个函数,该函数通过bashy在这里以人类可读的形式显示字节:

https://laracasts.com/discuss/channels/laravel/human-readable-file-size-and-time


推荐