3

I'm having a hard time finding a way to use (Compact Number Format) with NumberFormatter

As a reference here's a working example with JavaScript

new Intl.NumberFormat('en-GB', { 
    notation: "compact"
}).format(987654321);

// → 988M

new Intl.NumberFormat('en-GB', { 
    notation: "compact"
}).format(78656666589);

// → 79B

I used the below script to take a peek at available patters

$fmt = new NumberFormatter('en_US', NumberFormatter::DURATION);
var_dump($fmt->getPattern());

I've looked at

  • NumberFormatter::PATTERN_DECIMAL
  • NumberFormatter::DECIMAL
  • NumberFormatter::CURRENCY
  • NumberFormatter::PERCENT
  • NumberFormatter::SCIENTIFIC
  • NumberFormatter::SPELLOUT
  • NumberFormatter::ORDINAL

None of them has the compact pattern.

Does anyone have a working code for PHP? Or, potentially, compact pattern is not currently supported?

rock3t
  • 2,193
  • 2
  • 19
  • 24

2 Answers2

2

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.

jspit
  • 7,276
  • 1
  • 9
  • 17
  • Thank you @jspit I looked at this as an option B. Are you sure there's no "compact" pattern implementation in PHP? – rock3t Feb 08 '21 at 11:09
  • I am not sure. I found this solution by trying. In the description of the class in the PHP manual I didn't find anything about it. – jspit Feb 08 '21 at 11:29
0

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