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.
The getSymbol() method is used to get the symbol of a given currency for the default DISPLAY locale. For example, for the US Dollar, the symbol is "$" if the default locale is the US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217 currency code is returned.
The getSymbol() method is used to get the symbol of invoking currency for the default locale.
You can enter a custom currency symbol by going to WooCommerce > Settings > General Tab and looking down at the “Currency Options” section. There you will find the “Custom Currency Symbol” field.
Currency code / currency symbol If the three-letter currency code (ISO 4217) is used, it ALWAYS goes in front of the value. If currency symbols are used, some countries put the symbol in front, others behind the value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With