Magento – Magento 2 : How do conver price from any currency to base currency

currencycurrency-ratesmagento2multicurrency

I am converting price from any other currency using currency code to base currency and for this I am using this method :

$oldCurrency = 'AUD';
$newCurrency = 'USD';
$priceHelper = $objectManager->create('Magento\Directory\Helper\Data');
$priceHelper->currencyConvert($item->getCustomPrice(), $oldCurrency, $newCurrency); 

My base currency is USD and USD to AUD conversion rate is defined in admin.

When I am converting price from USD to AUD then its working, but when I am trying to convert price from AUD to USD then it gives me error that conversion rate is not defined.

How do I convert price from any currency to any other currency ?

Best Answer

NOTE: In the example the amount in current store currency is converting to amount in base store currency.

You can use this code to convert one currency to another:

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Magento\Directory\Model\CurrencyFactory
 */
protected $currencyFactory;

/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory
 */
public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Directory\Model\CurrencyFactory $currencyFactory
) {
    $this->storeManager = $storeManager;
    $this->currencyFactory = $currencyFactory;
}

/**
 * Convert base price value to store price value
 *
 * @param $amountValue
 * @return float
 */
public function convertPrice($amountValue)
{
    $currentCurrency = $this->storeManager->getStore()->getCurrentCurrency()->getCode();
    $baseCurrency = $this->storeManager->getStore()->getBaseCurrency()->getCode();
    if ($currentCurrency != $baseCurrency) {
        $rate = $this->currencyFactory->create()->load($currentCurrency)->getAnyRate($baseCurrency);
        $amountValue = $amountValue * $rate;
    }

    return $amountValue;
}

The $currentCurrency and $baseCurrency variables can be replaced by any valid currency codes from the currency collection.