Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active July 5, 2025 20:15
Show Gist options
  • Save stemar/00cb274845c859c32f05f46983225243 to your computer and use it in GitHub Desktop.
Save stemar/00cb274845c859c32f05f46983225243 to your computer and use it in GitHub Desktop.
Localize numeric value using encapsulated NumberFormatter functions
<?php
/**
* Localize numeric value using encapsulated NumberFormatter functions
*
* @param float $amount
* @param array $args
* @link https://www.php.net/manual/en/numberformatter.format.php
* @link https://www.php.net/manual/en/numberformatter.create.php
* @link https://www.php.net/manual/en/class.locale.php
* @link https://unicode.org/reports/tr35/tr35-numbers.html#table-number-pattern-character-definitions
* @return string|false
*/
function format_numeric($number, array $args = []) {
$args += [
'locale' => substr(Locale::getDefault(), 0, 5) ?: NULL,
'pattern' => NULL,
'style' => NumberFormatter::DEFAULT_STYLE,
'type' => NumberFormatter::TYPE_DEFAULT,
];
extract($args);
$formatter = numfmt_create($locale, $style, $pattern);
return numfmt_format($formatter, $number, $type);
}
function format_numeric_accounting($number, array $args = []) {
$args += [
'pattern' => '#,##0.00;(#,##0.00)',
'style' => NumberFormatter::PATTERN_DECIMAL,
];
return format_numeric($number, $args);
}
function format_numeric_spellout($number, array $args = []) {
$args += [
'style' => NumberFormatter::SPELLOUT,
];
return format_numeric($number, $args);
}
function format_numeric_ordinal($number, array $args = []) {
$args += [
'style' => NumberFormatter::ORDINAL,
];
return format_numeric($number, $args);
}
@stemar
Copy link
Author

stemar commented Apr 7, 2023

numfmt_create() arguments

numfmt_create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter

$locale

If NULL, it will lookup its default value in this order:

  1. ini_get('intl.default_locale')
  2. setlocale(LC_ALL, '0');
  3. $LANG value from the set locale of the operating system.

$style

$pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment