【问题标题】:Convert long numbers to short and compact将长数字转换为短而紧凑的数字
【发布时间】:2021-05-11 18:42:12
【问题描述】:

我很难找到将 (Compact Number Format) 与 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());

看过

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

它们都没有 compact 模式。

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

【问题讨论】:

    标签: php format intl


    【解决方案1】:

    您正在寻找 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 下测试过。

    【讨论】:

    • 谢谢@jspit 我将其视为选项 B。您确定 PHP 中没有“紧凑”模式实现吗?
    • 我不确定。我通过尝试找到了这个解决方案。在 PHP 手册中的类描述中,我没有找到任何关于它的内容。
    【解决方案2】:

    你可以使用这样的东西

        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
    

    【讨论】:

    • 不是我要找的,请再次阅读问题。
    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2023-03-23
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多