Learn how to exchange Magento 2 currency with the following steps in this blog.
In core Magento, it has charges from base currency to other currencies. It is quite simple to exchange currency from the base. However, if you need to exchange currency from current currency to base or other currencies. Core Magento doesn’t support this function. In this tutorial, we will do it by the following steps:
- Exchange currency from base to other currency
- Exchange currency from another currency to base currency
- Exchange currency from a currency to a currency
Build your Amazon-like multi-vendor marketplace website @ $249/- now!!!
Get your free live demo now: Click here
Exchange the Magento 2 currency
Exchange currency from base to other
$priceConverted = $this->_storeManager->getStore()->getBaseCurrency()->convert($price ,$toCurrency); With $this->_storeManager is Magento\Store\Model\StoreManagerInterface
Exchange currency from A currency to base currency
$rateToBase = $this->_currencyFactory->create()->load($fromCurrency)->getAnyRate($this->_storeManager->getStore()->getBaseCurrency()->getCode()); $priceConverted = $price * $rateToBase; With $this->_currencyFactory is \Magento\Directory\Model\CurrencyFactory
Exchange currency from a currency to a currency
public function currencyConvert($amount, $fromCurrency = null, $toCurrency = null) { if(!$fromCurrency){ $fromCurrency = $this->_storeManager->getStore()->getBaseCurrency(); } if(!$toCurrency){ $toCurrency = $this->_storeManager->getStore()->getCurrentCurrency(); } if (is_string($fromCurrency)) { $rateToBase = $this->_currencyFactory->create()->load($fromCurrency)->getAnyRate($this->_storeManager->getStore()->getBaseCurrency()->getCode()); } elseif ($fromCurrency instanceof \Magento\Directory\Model\Currency) { $rateToBase = $fromCurrency->getAnyRate($this->_storeManager->getStore()->getBaseCurrency()->getCode()); } $rateFromBase = $this->_storeManager->getStore()->getBaseCurrency()->getRate($toCurrency); if($rateToBase && $rateFromBase){ $amount = $amount * $rateToBase * $rateFromBase; } else { throw new InputException(__('Please correct the target currency.')); } return $amount; }
Click here to start a Magento store today with 300+ features in it.
Related:
- How to install Magento 2 on Mac OSX 10.1
- Why Magento owners leave Magento 2?
- Configure Color Swatches in Magento 2
- Change PDF Invoice Logo, Shipment logo in Magento 2
Leave a Reply