Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active April 19, 2023 05:18
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/00cb274845c859c32f05f46983225243 to your computer and use it in GitHub Desktop.
Save stemar/00cb274845c859c32f05f46983225243 to your computer and use it in GitHub Desktop.
Localize numeric value using encapsulated NumberFormatter functions
<?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);
}
@stemar
Copy link
Author

stemar commented Apr 7, 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