1

I have a block on Magento where I would like to display the price of the current product in the default display currency. This store has multiple currencies.

When I invoke $product->getPrice(), I get the price of the product converted into the current currency. I can convert this into the the default display currency using this method:

public function convertToBaseCurrency(StoreInterface $store, $amount)
{
    $rateToBase = $this->currencyFactory->create()->load($store->getCurrentCurrencyCode())->getAnyRate($store->getDefaultCurrencyCode());
    return $amount * $rateToBase;
}

The above sort-of works but leads to rounding and calculation discrepancies.

I have a product that is 22.00 EUR in the database. When viewing the product under CHF, I get a price of 23.50 CHF. The multiplier in the directory_currency_rate table for EUR > CHF is 1.068200000000, which means the product's price should be 23.5004 but somehow it gets rounded down. This basically means that I cannot convert back the price back to EUR wihout some minor discrepancies. I've vardumped the product and it indeed is 23.5 internally.

Having dug in deeper, I can see that the conversion happens and gets rounded. There's a constant that defines the rounding in PriceCurrencyInterface called DEFAULT_PRECISION

How should I get around this?

2
+25

AFAIK you should try to avoid writing your own method to convert the prices.

Stick to the following methods defined in Magento\Directory\Model\Currency:

  • convert($price, $toCurrency)
  • format($price, $options = [], $includeContainer = true, $addBrackets = false)

The first one converts a price to a currency (which is pretty much what you're doing in your custom method).

The second one formats the price by adding the rounding, the currency symbol and also the <span> container if you need it. You can change the precision by changing the second parameter to something like: $options['precision'] = 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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