Magento 2 – How to Convert Price from Current Currency to Base Currency

convertmagento2multicurrency

I want to convert product price from the current currency to base currency.

For Example, if the product price is 5000 INR. I want to convert 5000 INR to USD.

I don't know which core function will be best used for. Can anyone give me examples? Any function which is used for convert price to current to base and base to current?

Purpose: I am adding a product to cart programmatically, if a current currency is USD then it's working properly but if I switch currency as INR, added product price convert INR amount to USD. So I want to convert INR amount to USD.

Best Answer

Solution:

public function convertPrice($amount = 0, $store = null, $currency = null)
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $priceCurrencyObject = $objectManager->get('Magento\Framework\Pricing\PriceCurrencyInterface'); 
    //instance of PriceCurrencyInterface
    $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
    //instance of StoreManagerInterface
    if ($store == null) {
        $store = $storeManager->getStore()->getStoreId(); 
        //get current store id if store id not get passed
    }
    $rate = $priceCurrencyObject->convert($amount, $store, $currency); 
    //it return price according to current store from base currency
 
    //If you want it in base currency then use:
    $rate = $this->_priceCurrency->convert($amount, $store) / $amount;
    $amount = $amount / $rate;
     
    return $amount;

}

Here, $amount is the amount to which you want to convert.

$store is the store id, from which store’s base currency you want to convert.

$currency is the currency whom you want to convert, if you passed null then it takes current currency.

Related Topic