【问题标题】:How to get the currency symbol by currency code from the PHP Intl ( ICU library )如何通过 PHP Intl(ICU 库)中的货币代码获取货币符号
【发布时间】:2014-11-14 16:49:27
【问题描述】:

在 PHP 中,我知道货币代码(欧元、英镑、美元...),但我不知道语言环境。 我需要为他们获取货币符号

GBP -> £
EUR -> €
USD -> $

使用

$obj = new \NumberFormatter( null, \NumberFormatter::CURRENCY);
echo $obj->formatCurrency( null, 'EUR');

我可以获得 0.00 欧元,因此 NumberFormatter 库可以将货币代码转换为货币符号。 但是如何只获取货币符号呢?

$obj = new \NumberFormatter( null, \NumberFormatter::CURRENCY);
$obj->setTextAttribute ( \NumberFormatter::CURRENCY_CODE, 'EUR');
echo $obj->getSymbol ( \NumberFormatter::CURRENCY_SYMBOL);

也不做翻译,总是返回$。

【问题讨论】:

标签: php currency numberformatter


【解决方案1】:

不幸的是,这并不像应有的那么简单,但下面是如何通过货币代码获取货币符号的语言环境:

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;
}

测试语言环境:ar、cs、da、de、en、en_GB、en_US、es、fr、fr_CA、he、it、ja、ko、nb、nl、ru、sk、sv、zh

使用货币进行测试:AUD、BRL、CAD、CNY、EUR、GBP、HKD、ILS、INR、JPY、KRW、MXN、NZD、THB、TWD、USD、VND、XAF、XCD、XOF、XPF

【讨论】:

  • 我认为$zero = $formatter->getSymbol(NumberFormatter::ZERO_DIGIT_SYMBOL);不是必需的,您可以在最后一次操作0中使用$currencySymbol = str_replace(0, '', $formattedPrice);
  • 有一种更简单的解决方案。 Get currency symbol in PHP
  • @ZoltánSüle 好多了!谢谢!
  • 实际上,这种方式在某些情况下工作不正常(例如getCurrencySymbol("cs", "CZK")),会在字符串后面留下额外的字节。我猜,它破坏了 UTF-8。
【解决方案2】:

可能不是最好的解决方案,但你总是可以做类似...

$obj = new \NumberFormatter( 'en_us', \NumberFormatter::CURRENCY);
$formattedValue = $obj->formatCurrency( 0, 'EUR');
$currencySymbol = trim(str_replace('0.00','',$formattedValue));

重要的是使用您知道预期输出格式的语言环境和值(例如 en_us 和 0.00),然后您可以正确选择货币符号。

注意:这可能需要针对某些货币进行一些调整

【讨论】:

  • 这对于印度的货币将失败,因为它们使用不同的 0 (०) 以及使用其他符号的其他几个国家/地区。
猜你喜欢
  • 1970-01-01
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 2012-06-12
  • 1970-01-01
相关资源
最近更新 更多