Last active
July 5, 2025 20:16
-
-
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 $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); | |
} |
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
.Starting at 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.