Last active
April 4, 2023 00:44
-
-
Save stemar/64e8d61bbe9fb2d1e891b48c468f1c49 to your computer and use it in GitHub Desktop.
Localize currency using encapsulated NumberFormatter functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
numfmt_create() arguments
$locale
If
NULL
, it will lookup its default value in this order:ini_get('intl.default_locale')
setlocale(LC_ALL, '0');
$LANG
value from the set locale of the operating system.$style
https://www.php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatstyle
For currency, it's
NumberFormatter::CURRENCY
.For PHP version 7.4.1, there is
NumberFormatter::CURRENCY_ACCOUNTING
to format amounts with parentheses.$pattern
https://unicode.org/reports/tr35/tr35-numbers.html#table-number-pattern-character-definitions
If not
NULL
, it will override the style argument.If
NULL
, it will defer to the style argument.