Skip to content

Instantly share code, notes, and snippets.

@PovilasKorop
Created February 14, 2022 06:24
Show Gist options
  • Save PovilasKorop/e099159e1d513cfdf39d13c24e22992b to your computer and use it in GitHub Desktop.
Save PovilasKorop/e099159e1d513cfdf39d13c24e22992b to your computer and use it in GitHub Desktop.
PHP NumberFormatter Demo
<?php
function getFormattedNumber(
$value,
$locale = 'en_US',
$style = NumberFormatter::DECIMAL,
$precision = 2,
$groupingUsed = true,
$currencyCode = 'USD',
) {
$formatter = new NumberFormatter($locale, $style);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
$formatter->setAttribute(NumberFormatter::GROUPING_USED, $groupingUsed);
if ($style == NumberFormatter::CURRENCY) {
$formatter->setTextAttribute(NumberFormatter::CURRENCY_CODE, $currencyCode);
}
return $formatter->format($value);
}
echo getFormattedNumber(12345678.9);
echo '<br />';
echo getFormattedNumber(
value: 12345678.9,
locale: 'pt_BR'
);
echo '<br />';
echo getFormattedNumber(
value: 12345678.9,
locale: 'fr_FR'
);
echo '<br />';
echo getFormattedNumber(
value: 12345678.90,
precision: 1
);
echo '<br />';
echo getFormattedNumber(
value: 12345678.90,
groupingUsed: false
);
echo '<br />';
echo getFormattedNumber(
value: 12345678.90,
locale: 'fr_FR',
style: NumberFormatter::CURRENCY,
currencyCode: 'EUR',
);
echo '<br />';
echo getFormattedNumber(
value: 12345678,
style: NumberFormatter::PADDING_POSITION,
precision: 3
);
echo '<br />';
echo getFormattedNumber(
value: 12345678,
style: NumberFormatter::SPELLOUT
);
echo '<br />';
echo getFormattedNumber(
value: 0.123,
style: NumberFormatter::PERCENT,
precision: 1
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment