Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the currency symbol by currency code from the PHP Intl ( ICU library )

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.

like image 851
Joe Avatar asked Nov 14 '14 16:11

Joe


People also ask

How do you make the currency symbol?

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.

How do I get the currency symbol from locale?

The getSymbol() method is used to get the symbol of invoking currency for the default locale.

How do I get the currency symbol in WooCommerce?

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.

Where do currency codes go?

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.


1 Answers

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

like image 141
Brandon Kelly Avatar answered Oct 13 '22 01:10

Brandon Kelly