What Does '6k views' mean and how can I fo

2020-02-20 05:27发布

What does "6k views" mean and how can I format this number in PHP?

标签: php
7条回答
三岁会撩人
2楼-- · 2020-02-20 05:54

Abridged from http://tamlyn.org/2008/12/formatting-bytes-with-significant-figures-in-php/

/** Calculate $value to $sigFigs significant figures */
function sigFig($value, $sigFigs = 3) {
    //convert to scientific notation e.g. 12345 -> 1.2345x10^4
    //where $significand is 1.2345 and $exponent is 4
    $exponent = floor(log10(abs($value))+1);
    $significand = round(($value
        / pow(10, $exponent))
        * pow(10, $sigFigs))
        / pow(10, $sigFigs);
    return $significand * pow(10, $exponent);
}

/** Format $value with the appropriate SI prefix symbol */
function format($value, $sigFigs = 3)
{
    //SI prefix symbols
    $units = array('', 'k', 'M', 'G', 'T', 'P', 'E');
    //how many powers of 1000 in the value?
    $index = floor(log10($value)/3);
    $value = $index ? $value/pow(1000, $index) : $value;
    return sigFig($value, $sigFigs) . $units[$index];
}

Doing *11 because *10 is too obvious

for($number = 100; $number < 100000000000000000000; $number*=11) {
   echo format($number), PHP_EOL;
}

gives

100 1.1k 12.1k 133k 1.46M 16.1M 177M 1.95G 21.4G 236G 2.59T 28.5T 314T 3.45P 38P 418P 4.59E 50.5E 

If you need the decimals, use the above, else Gumbo's solution is more compact. Gives:

100 1k 12k 133k 1M 16M 177M 1G 21G 235G 2T 28T 313T 3P 37P 417P 4E 50E
查看更多
登录 后发表回答