How can I show base currency price & display currency price at the same time in magento2?
-
02-10-2020 - |
Question
I would like to show product price in both base currency & display currency.
I have already enable display currency in frontend - that is i can see "USD / YEN" in header dropdown menu.
For display price with format price, i used this code to handle:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of Object Manager
$priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data'); // Instance of Pricing Helper
$price = 1000; //Your Price
$formattedPrice = $priceHelper->currency($price, true, false);
If i want to show 2 price, one in base currency, one in display currency at the same time, what should be the correct way?
Solution
Finally find out the code to show both display currency & base currency.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$priceCurrencyObject = $objectManager->get('Magento\Framework\Pricing\PriceCurrencyInterface');
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore()->getStoreId();
$base = "USD";
$rate = $priceCurrencyObject->convert($block->getDisplayValue(), $store, $base);
$amount = $block->getDisplayValue();
//If you want it in base currency then use:
$current_currency = $storeManager->getStore()->getCurrentCurrency()->getCode();
if ($current_currency!=$base) {
$rate = $helper->priceCurrency->convert($amount, $store) / $amount;
$amount = $amount / $rate;
echo " (";
echo $helper->priceCurrency->getCurrencySymbol(false, $base);
echo $priceCurrencyObject->round($amount);
echo ")";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange