10

I have a setup with two store views.

The first store view has base and the only one currency set to USD. The second one has 2 allowed currencies - USD and EUR. EUR is the default displayed one, USD is set as a base one.

All products' prices are set only in USD and the exchange rate for EUR is set to 0.75. Price of the product is let's say $14.

And my code goes:

// Store ID 2 - default currency EUR, base currency USD
// $product is instance of Magento\Catalog\Model\Product
$priceInfo = $product->getPriceInfo();
$price = $priceInfo->getPrice('regular_price')->getValue();

This code always fetch the correct price (10.50) in EUR. But I need both prices - in USD and in EUR, but I didn't find a way on how to pass currency to any getPrice method.

I tried to use Magento\Directory\Helper\Data to convert:

$helper->currencyConvert($price, 'EUR', 'USD');

But it gives me $13.99 when the real price in USD is $14 - so the calculation is wrong.

Do you know how can I get product's prices for both store currencies? Thanks a lot!

2 Answers 2

2

When you feel like 'the calculation is wrong', it always helps to look at the source code. When I look at \Magento\Directory\Model\Currency::convert() (this is the inner method that \Magento\Directory\Helper\Data::currencyConvert() uses), I see something interesting:

public function convert($price, $toCurrency = null)
{
    if ($toCurrency === null) {
        return $price;
    } elseif ($rate = $this->getRate($toCurrency)) {
        return $price * $rate;
    }

This means that it converts the price to the rate that is set in the $toCurrency. In your example your convert EUR to USD. I guess the rate of USD is 1.00, so when you're converting 14 USD * 1.00, you get 13.99 (I guess this is due to how floating numbers work?).

How to solve this? Well, you have your base price in USD, and you know that EUR has a rate of 0.75, so if you have code that fetches the base price of your product, loads the EUR rate and multiplies it with that you might be set to go. For example:

$basePrice = $product->getPrice();
$currency  = $currencyFactory->create()->load('EUR');
$eurPrice  = $currency->convert($basePrice, 'EUR');

Haven't tested it yet so I'm not sure if it works, only following the code. But perhaps it helps you finding your solution.

2

Kindly use below code

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productId = 46;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load(productId );
$price = $product->getFinalPrice();
$currency = $objectManager->create('Magento\Directory\Model\Currency')->load('USD');
echo $currency->convert($price,'EUR');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.