Last active
July 5, 2025 20:15
-
-
Save stemar/00cb274845c859c32f05f46983225243 to your computer and use it in GitHub Desktop.
Localize numeric value 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 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); | |
} |
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
The numeric default is
NumberFormatter::DEFAULT_STYLE
.$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.