How to convert default currency to others in Magento?

To convert default currency to others, select the currency and import currency rates from System-> Manage currency-> Rates.

Syntax:

$convertedPrice = Mage::helper(‘directory’)->currencyConvert($price, currentCurrency, newCurrency);

In Magento, you can convert the default currency to other currencies programmatically by utilizing the currency conversion functionality provided by the framework. Here’s how you can achieve this:

  1. Load the Store Configuration: First, load the store configuration to get the base currency code.
  2. Load the Currency Model: Use Magento’s currency model to load the currency rates.
  3. Convert Currency: Utilize the loaded currency rates to convert the default currency to the desired currency.

Here’s a code snippet demonstrating this process:

php
<?php

use Magento\Store\Model\StoreManagerInterface;
use Magento\Directory\Model\CurrencyFactory;

class CurrencyConverter
{
protected $storeManager;
protected $currencyFactory;

public function __construct(
StoreManagerInterface $storeManager,
CurrencyFactory $currencyFactory
)
{
$this->storeManager = $storeManager;
$this->currencyFactory = $currencyFactory;
}

public function convertCurrency($amount, $toCurrencyCode)
{
$store = $this->storeManager->getStore();
$baseCurrencyCode = $store->getBaseCurrencyCode();
$currency = $this->currencyFactory->create();

$rate = $currency->load($toCurrencyCode)->getAnyRate($baseCurrencyCode);
if ($rate) {
return $amount * $rate;
}

// If conversion rate not available, return null or handle accordingly
return null;
}
}

// Example Usage:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$converter = $objectManager->create(CurrencyConverter::class);

// Convert 100 USD to Euro
$amount = 100;
$convertedAmount = $converter->convertCurrency($amount, 'EUR');
echo "Converted Amount: " . $convertedAmount;

Remember to replace \Magento\Framework\App\ObjectManager::getInstance() with dependency injection or service contract whenever possible. This code retrieves an instance of the currency converter service and uses it to convert a specified amount from the base currency to the desired currency code provided.

This approach ensures accurate conversion by using the currency rates defined in Magento’s configuration.