phpnumberformatter

PHP NumberFormatter add grouping for 5+ digit numbers?


I'm trying to fix a formatting error in the PHP NumberFormatter class for my language, Bulgarian: thousands grouping is only introduced for 5+ digit numbers, i.e. "5 000" is wrong.

Is there a predefined constant I can use?

I thought this would be NumberFormatter::GROUPING_SIZE but this doesn't take into consideration the above rule. Should I be looking for some other attribute or is what I'm trying to do not possible?


Solution

  • While it's not likely to be able to do this directly, you can use a wrapper class that modifies the output to what you expect:

    class BulgarianNumberFormatter extends \NumberFormatter
    {
        public function __construct(
            string|null $locale = 'bg_BG',
            int $style = null,
            string $pattern = null
        ) {
            parent::__construct($locale, $style, $pattern);
        }
    
        public function format(
            int|float $num,
            int $type = self::TYPE_DEFAULT
        ): string|false {
            $numOfWholeDigits = $num != 0 ? floor(log10($num) + 1) : 1;
            $formatted = parent::format($num, $type);
            if($numOfWholeDigits < 6) {
                $formatted = str_replace(
                    $this->getSymbol(static::GROUPING_SEPARATOR_SYMBOL),
                    '',
                    $formatted
                );
            }
            return $formatted;
        }
    }
    

    To use:

    require_once('/path/to/BulgarianNumberFormatter.php');
    // or
    use Namespace\Of\BulgarianNumberFormatter;
    
    $formatter = new BulgarianNumberFormatter(style:\NumberFormatter::DECIMAL);
    
    $formatter->format(5000);       // 5000
    $formatter->format(120500);     // 120 500
    $formatter->format(10005000);   // 10 005 000
    $formatter->format(3210005000); // 3 210 005 000
    

    As a note, the INTL extension is not run directly by PHP. It is a wrapper for the ICU library that is available on just about every system and used for formatting & translation - even by web browsers. If you think this should be changed in the ICU library, you can request changes here: https://icu.unicode.org/bugs