php - Convert long numbers to short and compact

Solution:

You are looking for NumberFormatter::PADDING_POSITION.

$fmt = new NumberFormatter('en_US', NumberFormatter::PADDING_POSITION);

for($i=1;$i<1.E10;$i *=10){
  echo $i.' => '.$fmt->format($i)."<br>\n";
}
/*
1 => 1
10 => 10
100 => 100
1000 => 1K
10000 => 10K
100000 => 100K
1000000 => 1M
10000000 => 10M
100000000 => 100M
1000000000 => 1B
*/

I tested it under PHP 7.4.2.

Answer

Solution:

You can use something like this

    function compact_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",","",$n));
       
        // is this a number?
        if(!is_numeric($n)) return false;
       
        // now filter it;
        if($n>1000000000000) return round(($n/1000000000000),1).' T';
        else if($n>1000000000) return round(($n/1000000000),1).' B';
        else if($n>1000000) return round(($n/1000000),1).' M';
        else if($n>1000) return round(($n/1000),1).' K';
       
        return number_format($n);
    }

echo compact_number(247704360);
echo compact_number(866965260000);

//    Outputs:

// 247704360 -> 247.7 M
// 866965260000 -> 867 B

Source