Reputation: 395
In PHP I know currency codes (EUR, GBP, USD...), but I do not know locale. I need to get a currency symbol for them
GBP -> £
EUR -> €
USD -> $
Using
$obj = new \NumberFormatter( null, \NumberFormatter::CURRENCY);
echo $obj->formatCurrency( null, 'EUR');
I can get € 0.00, so the NumberFormatter library can convert currency code to currency symbol. But how to get currency symbol only?
$obj = new \NumberFormatter( null, \NumberFormatter::CURRENCY);
$obj->setTextAttribute ( \NumberFormatter::CURRENCY_CODE, 'EUR');
echo $obj->getSymbol ( \NumberFormatter::CURRENCY_SYMBOL);
Also do not do the translation and returns $ always.
Upvotes: 6
Views: 6997
Reputation: 2163
Unfortunately this isn’t as easy as it should be, but here’s how to get the currency symbol by currency code, for a locale:
function getCurrencySymbol($locale, $currency)
{
// Create a NumberFormatter
$formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
// Prevent any extra spaces, etc. in formatted currency
$formatter->setPattern('¤');
// Prevent significant digits (e.g. cents) in formatted currency
$formatter->setAttribute(NumberFormatter::MAX_SIGNIFICANT_DIGITS, 0);
// Get the formatted price for '0'
$formattedPrice = $formatter->formatCurrency(0, $currency);
// Strip out the zero digit to get the currency symbol
$zero = $formatter->getSymbol(NumberFormatter::ZERO_DIGIT_SYMBOL);
$currencySymbol = str_replace($zero, '', $formattedPrice);
return $currencySymbol;
}
Tested with locales: ar, cs, da, de, en, en_GB, en_US, es, fr, fr_CA, he, it, ja, ko, nb, nl, ru, sk, sv, zh
Tested with currencies: AUD, BRL, CAD, CNY, EUR, GBP, HKD, ILS, INR, JPY, KRW, MXN, NZD, THB, TWD, USD, VND, XAF, XCD, XOF, XPF
Upvotes: 11
Reputation: 76
Possibly not the best solution but you could always do something like ...
$obj = new \NumberFormatter( 'en_us', \NumberFormatter::CURRENCY);
$formattedValue = $obj->formatCurrency( 0, 'EUR');
$currencySymbol = trim(str_replace('0.00','',$formattedValue));
The important thing is using a locale and value where you know the expected output format (e.g. en_us and 0.00) and you can then pick the currency symbol out correctly.
Note: this might need some adjustment for certain currencies
Upvotes: -1