Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active July 5, 2025 20:16
Show Gist options
  • Save stemar/64e8d61bbe9fb2d1e891b48c468f1c49 to your computer and use it in GitHub Desktop.
Save stemar/64e8d61bbe9fb2d1e891b48c468f1c49 to your computer and use it in GitHub Desktop.
Localize currency using encapsulated NumberFormatter functions
<?php
/**
* Localize currency using encapsulated NumberFormatter functions
*
* @param float $amount
* @param array $args
* @link https://www.php.net/manual/en/numberformatter.formatcurrency.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_currency($amount, array $args = []) {
$args += [
'locale' => substr(Locale::getDefault(), 0, 5) ?: NULL,
'pattern' => NULL,
'style' => NumberFormatter::CURRENCY,
];
extract($args);
$formatter = numfmt_create($locale, $style, $pattern);
$symbol = numfmt_get_symbol($formatter, NumberFormatter::INTL_CURRENCY_SYMBOL);
return numfmt_format_currency($formatter, $amount, $symbol);
}
function format_currency_accounting($amount, $space = FALSE, array $args = []) {
$args += [
'pattern' => $space ? '¤ #,##0.00;(¤ #,##0.00)' : '¤#,##0.00;(¤#,##0.00)',
'style' => NumberFormatter::PATTERN_DECIMAL,
];
return format_currency($amount, $args);
}
@stemar
Copy link
Author

stemar commented Apr 3, 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