phpfunctionhelper

Shorten long numbers to K/M/B?


I've googled this a lot but i can't find any helpful functions based on my queries.

What i want is:

100 -> 100
1000 -> 1,000
142840 -> 142,840

BUT

2023150 -> 2.023M ( i still want 3 additional numbers for more accuracy )
5430120215 -> 5.430B

I would totally appreciate any custom functions to dynamically choose the limit if possible.


Solution

  • Use number_format():

    if ($n < 1000000) {
        // Anything less than a million
        $n_format = number_format($n);
    } 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';
    }
    

    I would totally appreciate any custom functions to dynamically choose the limit if possible.

    If "limit" refers to the number of decimal places (the precision), that's easy:

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