Last active
April 19, 2023 05:18
-
-
Save stemar/00cb274845c859c32f05f46983225243 to your computer and use it in GitHub Desktop.
Localize numeric value using encapsulated NumberFormatter functions
This file contains 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 $kwargs | |
* @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 | |
* @return string|false | |
*/ | |
function numeric_format($number, array $kwargs = []) { | |
extract($kwargs + [ | |
'locale' => substr(Locale::getDefault(), 0, 5) ?: NULL, | |
'pattern' => NULL, | |
'style' => NumberFormatter::DEFAULT_STYLE, | |
'type' => NumberFormatter::TYPE_DEFAULT, | |
]); | |
$fmt = numfmt_create($locale, $style, $pattern); | |
return numfmt_format($fmt, $number, $type); | |
} | |
/** | |
* Variants | |
*/ | |
function spellout_format($number, array $kwargs = []) { | |
$kwargs['style'] = NumberFormatter::SPELLOUT; | |
return numeric_format($number, $kwargs); | |
} | |
function ordinal_format($number, array $kwargs = []) { | |
$kwargs['style'] = NumberFormatter::ORDINAL; | |
return numeric_format($number, $kwargs); | |
} |
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.