Today we will talk about an old feature of php that appeared in version 5.3.0 in converting numbers into different languages depending on the country and is coordinated with commas and periods. I found this wonderful information in the source https://www.youtube.com/watch?v=O9Bk4mNjXZg
<?php
function getFormattedNumber(
$value,
$locale = 'ar_EG',
$style = NumberFormatter::DECIMAL,
$precision = 2,
$groupingUsed = true,
$currencyCode = 'EGP',
) {
$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 getFormattedNumber(
value: 12345678.9,
locale: 'pt_BR'
); //12.345.678,90
echo getFormattedNumber(
value: 12345678.9,
locale: 'fr_FR'
); //12 345 678,90
echo getFormattedNumber(
value: 12345678.90,
precision: 1
); //١٢٬٣٤٥٬٦٧٨٫٩
echo getFormattedNumber(
value: 12345678.90,
groupingUsed: false
); //١٢٣٤٥٦٧٨٫٩٠
echo getFormattedNumber(
value: 12345678.90,
locale: 'fr_FR',
style: NumberFormatter::CURRENCY,
currencyCode: 'EUR',
); //12 345 678,90 €
echo getFormattedNumber(
value: 12345678,
style: NumberFormatter::PADDING_POSITION,
precision: 3
); //١٢٫٣٤٦ مليون
echo getFormattedNumber(
value: 12345678,
style: NumberFormatter::SPELLOUT
); //إثنا عشر مليون و ثلاثة مائة و خمسة و أربعون ألف و ستة مائة و ثمانية و سبعون
echo getFormattedNumber(
value: 0.123,
style: NumberFormatter::PERCENT,
precision: 1
); //١٢٫٣٪
If you want to dig deeper and enjoy the code, please visit these resources https://www.php.net/manual/en/class.numberformatter.php
https://www.xe.com/iso4217.php
https://gist.github.com/PovilasKorop/e099159e1d513cfdf39d13c24e22992b
https://stackoverflow.com/questions/30554177/fatal-error-class-numberformatter-not-found
Top comments (0)