Trying to format the number as a currency amount and add the relative ISO code as suffix.
$NumberFormatter = new NumberFormatter(MY_LOCALE, NumberFormatter::CURRENCY);
$NumberFormatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, "");
$NumberFormatter->formatCurrency($Amount, $CurrencyCode="EUR");
This will produce "10,00" if $CurrencyCode=EUR but "10,00 DKK" or "10,00 RUB" for $CurrencyCode=DKK, $CurrencyCode=RUB
Why isn’t it behaving consistently?
I would like it to return just the amount, without currency symbol nor ISO code, so that I can add the ISO code afterwards.
Using PHP 8.2.8 on a Debian.
2
Answers
The above will: a) remove the currency symbol, b) retain the currency-specific number of fraction digits, c) retain the locale-specific fraction digits and thousands separator chars, d) add the ISO currency code after the formatted amount
That’s the point of the
NumberFormatter
class. It uses a huge set of rules that have been compiled for eachLocale
. If that locale’s rules say only include the number (for instance, if the locale matches the existing currency), then it will only show that. But if you specify a currency code that does is different, based on the rules, will likely display the currency so the user does not get confused over what currency is being displayed. The rules are based on what a majority of people generally expect as far as formatting currency or numbers in general for the specified locale.That being said, if you just want a basic formatted number, you can just use the DECIMAL basic formatter:
You can then add your own currency symbol and/or codes. However, the way your code was set up was mostly correct and would provide the proper symbol and/or code in the correct locations for the locale. Adding them on your own may confuse people in certain locales.