Magento 2: get the current currency code
In a block
In Magento 2, you can use the \Magento\Store\Model\StoreManagerInterface
which is stored in an accessible variable $_storeManager
for every class extending \Magento\Framework\View\Element\Template
so most of the block classes (Template
, Messages
, Redirect
block types but not Text
nor TextList
).
This way in your block, you can directly type the following code to get the current currency code:
$this->_storeManager->getStore()->getCurrentCurrency()->getCode()
No need to inject the \Magento\Store\Model\StoreManagerInterface
in your construct as it's a variable accessible from any block class.
In any other class
You can inject the \Magento\Store\Model\StoreManagerInterface
in your constructor:
protected $_storeManager;
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
{
$this->_storeManager = $storeManager;
}
Then call the same function as the block:
$this->_storeManager->getStore()->getCurrentCurrency()->getCode()
This takes inspiration from Magento\Framework\Pricing\Render\Amount
and it's working good in my case (behaving like Magento):
protected $_priceCurrency;
public function __construct(
...
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
...
)
{
$this->_priceCurrency = $priceCurrency;
...
}
/**
* Get current currency code
*
* @return string
*/
public function getCurrentCurrencyCode()
{
return $this->_priceCurrency->getCurrency()->getCurrencyCode();
}
You can get the currency symbol also:
/**
* Get current currency symbol
*
* @return string
*/
public function getCurrentCurrencySymbol()
{
return $this->_priceCurrency->getCurrency()->getCurrencySymbol();
}