Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active April 4, 2023 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 $kwargs
* @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
* @return string|false
*/
function currency_format($amount, array $kwargs = []) {
extract($kwargs + [
'locale' => substr(Locale::getDefault(), 0, 5) ?: NULL,
'pattern' => NULL,
]);
$fmt = numfmt_create($locale, NumberFormatter::CURRENCY, $pattern);
$symbol = numfmt_get_symbol($fmt, NumberFormatter::INTL_CURRENCY_SYMBOL);
return numfmt_format_currency($fmt, $amount, $symbol);
}
@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