Unix Man Unix Man - 9 days ago 5
PHP Question

What Does '6k views' mean and how can I format the number in PHP

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

Answer

k is the abbreviation for the Kilo prefix and means thousand. So 6k means six thousand.

You can format a number in such a way with the following function using division:

function format($number) {
    $prefixes = 'kMGTPEZY';
    if ($number >= 1000) {
        for ($i=-1; $number>=1000; ++$i) {
            $number /= 1000;
        }
        return floor($number).$prefixes[$i];
    }
    return $number;
}

Or using logarithm base 10 and exponentiation:

function format($number) {
    $prefixes = 'kMGTPEZY';
    if ($number >= 1000) {
        $log1000 = floor(log10($number)/3);
        return floor($number/pow(1000, $log1000)).$prefixes[$log1000-1];
    }
    return $number;
}
Comments