将长数字转换为短而紧凑的数字

Convert long numbers to short and compact

我很难找到使用方法 (Compact Number Format) with NumberFormatter

作为参考,这里有一个 JavaScript

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

// → 988M

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

// → 79B

我使用下面的脚本来查看可用的模式

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

我看过

None 个具有 紧凑 模式。

有人有 PHP 的工作代码吗? 或者,目前不支持 compact 模式?

你可以使用这样的东西

    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

您正在寻找 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
*/

我在PHP 7.4.2下测试过。