php - If a number is too large use an abbreviation

Solution:

First of all, your function:

function convert($num_likes)
{
    $num_likes = $number / 1000;
    return $num_likes . 'k';
}

will not work as expected, because it converts to the opposite way :) Here is updated version:

function convert($num_likes)
{
    $number = $num_likes / 1000;
    return $number . 'k';
}

Second point. You should use the function somewhere... for example your line (actually only a part of it):

<p> Total Likes: " . $num_likes ."</p>

must be:

<p> Total Likes: " . convert($num_likes) ."</p>

And finally, using this answer we can modify convert function to this:

function convert($n) {
    if ($n < 1000) {
        $n_format = number_format($n);
    } else if ($n < 1000000) {
        // Anything less than a million
        $n_format = number_format($n / 1000, 3) . 'k';
    } else if ($n < 1000000000) {
        // Anything less than a billion
        $n_format = number_format($n / 1000000, 3) . 'M';
    } else {
        // At least a billion
        $n_format = number_format($n / 1000000000, 3) . 'B';
    }
    return $n_format;
}

Now we can convert all numbers up to billions.

Playground: click.

Answer

Solution:

Perhaps like this,

Use round() if you don't want large fractions.

<?php
function convert(int $number)
{
    if ($number >= 1E9) {
        return round($number / 1E9, 2).'b';
    } else if ($number >= 1E6) {
        return round($number / 1E6, 2).'m';
    } else if ($number >= 1E3) {
        return round($number / 1E3, 2).'k';
    }
    return $number;
}

echo convert(1000000000).PHP_EOL; // 1b
echo convert(1000000).PHP_EOL;    // 1m
echo convert(1200).PHP_EOL;       // 1.2k
echo convert(1234).PHP_EOL;       // 1.23k
echo convert(100).PHP_EOL;        // 100

https://3v4l.org/cc54H

Source