Site icon MageComp Blog

[Solved] Magento 2: Currency Symbol not Showing on Product, Cart and Checkout Page

Currency Symbol not Showing on Product, Cart and Checkout Page in m2

Hello Magento Friends,

Facing the issue of currency symbol not being displayed on the product, cart, and checkout page in Magento 2? I am here to provide a solution to this problem.

For a global reach of customers, it is necessary to display product prices on the basis of customers’ locality. A Magento store that supports different types of currencies can enhance the shopping experience of its customers. Automatically switch currency of the Magento 2 store based on the user’s location and provide flexibility of payment.

Learn How to Configure Currency in Magento 2

You have configured currency properly but sometimes you face issues with currency symbols. After you upgrade to Magento 2.4.3, it may happen that the currency symbol is not displayed on the product page, cart page, or checkout page. Let’s solve this issue

Steps to Solve Currency Symbol not Showing on Product, Cart and Checkout Page in Magento 2:

Step 1: First, we need to create a “di.xml” file inside our extension at the following path.

app\code\Vendor\Extension\etc\

Then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Directory\Model\Currency" type="Vendor\Extension\Model\Currency" />
</config>

Step 2: After that, we need to create a “Currency.php” file inside the below path folder to add a file in the module.

 app\code\Vendor\Extension\Model\

Then add the code as mentioned underneath

<?php
namespace Vendor\Extension\Model;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\InputException;
use Magento\Directory\Model\Currency\Filter;
use Magento\Framework\Locale\Currency as LocaleCurrency;
use Magento\Framework\Locale\ResolverInterface as LocalResolverInterface;
use Magento\Framework\NumberFormatterFactory;
use Magento\Framework\Serialize\Serializer\Json;

class Currency extends \Magento\Directory\Model\Currency
{
    protected function _construct()
    {
        $this->_init(\Magento\Directory\Model\ResourceModel\Currency::class);
    }
    public function getCode()
    {
        return $this->_getData('currency_code');
    }
    public function getCurrencyCode()
    {
        return $this->_getData('currency_code');
    }
    public function getRates()
    {
        return $this->_rates;
    }
    public function setRates(array $rates)
    {
        $this->_rates = $rates;
        return $this;
    }
    public function load($id, $field = null)
    {
        $this->unsRate();
        $this->setData('currency_code', $id);
        return $this;
    }
    public function getRate($toCurrency)
    {
        $code = $this->getCurrencyCodeFromToCurrency($toCurrency);
        $rates = $this->getRates();
        if (!isset($rates[$code]))
        {
            $rates[$code] = $this->_getResource()->getRate($this->getCode(), $toCurrency);
            $this->setRates($rates);
        }
        return $rates[$code];
    }
    public function getAnyRate($toCurrency)
    {
        $code = $this->getCurrencyCodeFromToCurrency($toCurrency);
        $rates = $this->getRates();
        if (!isset($rates[$code]))
        {
            $rates[$code] = $this->_getResource()->getAnyRate($this->getCode(), $toCurrency);
            $this->setRates($rates);
        }
        return $rates[$code];
    }
    public function convert($price, $toCurrency = null)
    {
        if ($toCurrency === null)
        {
            return $price;
        } elseif ($rate = $this->getRate($toCurrency))
        {
            return (float)$price * (float)$rate;
        }

        throw new \Exception(__(
            'Undefined rate from "%1-%2".',
            $this->getCode(),
            $this->getCurrencyCodeFromToCurrency($toCurrency)
        ));
    }
    private function getCurrencyCodeFromToCurrency($toCurrency)
    {
        if (is_string($toCurrency))
        {
            $code = $toCurrency;
        } elseif ($toCurrency instanceof \Magento\Directory\Model\Currency)
        {
            $code = $toCurrency->getCurrencyCode();
        } else
        {
            throw new InputException(__('Please correct the target currency.'));
        }
        return $code;
    }
    public function getFilter()
    {
        if (!$this->_filter)
        {
            $this->_filter = $this->_currencyFilterFactory->create(['code' => $this->getCode()]);
        }
        return $this->_filter;
    }
    public function format($price, $options = [], $includeContainer = true, $addBrackets = false)
    {
        return $this->formatPrecision($price, 2, $options, $includeContainer, $addBrackets);
    }
    public function formatPrecision(
        $price,
        $precision,
        $options = [],
        $includeContainer = true,
        $addBrackets = false
    ) {
        if (!isset($options['precision']))
        {
            $options['precision'] = $precision;
        }
        if ($includeContainer)
        {
            return '<span class="price">' . ($addBrackets ? '[' : '') . $this->formatTxt(
                $price,
                $options
            ) . ($addBrackets ? ']' : '') . '</span>';
        }
        return $this->formatTxt($price, $options);
    }
    public function formatTxt($price, $options = [])
    {
        if (!is_numeric($price))
        {
            $price = $this->_localeFormat->getNumber($price);
        }
        $price = sprintf("%F", $price);
     
       /* if ($this->canUseNumberFormatter($options))
        {
            return $this->formatCurrency($price, $options);
        }*/

        return $this->_localeCurrency->getCurrency($this->getCode())->toCurrency($price, $options);
    }
    private function canUseNumberFormatter(array $options): bool
    {
        $allowedOptions = [
            'precision',
            LocaleCurrency::CURRENCY_OPTION_DISPLAY,
            LocaleCurrency::CURRENCY_OPTION_SYMBOL
        ];

        if (!empty(array_diff(array_keys($options), $allowedOptions)))
        {
            return false;
        }

        if (array_key_exists('display', $options)
            && $options['display'] !== \Magento\Framework\Currency::NO_SYMBOL
            && $options['display'] !== \Magento\Framework\Currency::USE_SYMBOL
        ) {
            return false;
        }

        return true;
    }
    private function formatCurrency(string $price, array $options): string
    {
        $customerOptions = new \Magento\Framework\DataObject([]);

        $this->_eventManager->dispatch(
            'currency_display_options_forming',
            ['currency_options' => $customerOptions, 'base_code' => $this->getCode()]
        );
        $options += $customerOptions->toArray();

        $this->numberFormatter = $this->getNumberFormatter($options);

        $formattedCurrency = $this->numberFormatter->formatCurrency(
            $price, $this->getCode() ?? $this->numberFormatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE)
        );

        if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_SYMBOL, $options))
        {
            // remove only one non-breaking space from custom currency symbol to allow custom NBSP in currency symbol
            $formattedCurrency = preg_replace('/ /u', '', $formattedCurrency, 1);
        }

        if ((array_key_exists(LocaleCurrency::CURRENCY_OPTION_DISPLAY, $options)
                && $options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::NO_SYMBOL))
        {
            $formattedCurrency = str_replace(' ', '', $formattedCurrency);
        }

        return preg_replace('/^\s+|\s+$/u', '', $formattedCurrency);
    }
    private function getNumberFormatter(array $options): \Magento\Framework\NumberFormatter
    {
        $key = 'currency_' . md5($this->localeResolver->getLocale() . $this->serializer->serialize($options));
        if (!isset($this->numberFormatterCache[$key]))
        {
            $this->numberFormatter = $this->numberFormatterFactory->create(
                ['locale' => $this->localeResolver->getLocale(), 'style' => \NumberFormatter::CURRENCY]
            );

            $this->setOptions($options);
            $this->numberFormatterCache[$key] = $this->numberFormatter;
        }

        return $this->numberFormatterCache[$key];
    }
    private function setOptions(array $options): void
    {
        if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_SYMBOL, $options))
        {
            $this->numberFormatter->setSymbol(
                \NumberFormatter::CURRENCY_SYMBOL, $options[LocaleCurrency::CURRENCY_OPTION_SYMBOL]
            );
        }
        if (array_key_exists(LocaleCurrency::CURRENCY_OPTION_DISPLAY, $options)
            && $options[LocaleCurrency::CURRENCY_OPTION_DISPLAY] === \Magento\Framework\Currency::NO_SYMBOL)
        {
            $this->numberFormatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, '');
        }
        if (array_key_exists('precision', $options))
        {
            $this->numberFormatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $options['precision']);
        }
    }
    public function getCurrencySymbol()
    {
        return $this->_localeCurrency->getCurrency($this->getCode())->getSymbol();
    }
    public function getOutputFormat()
    {
        $formatted = $this->formatTxt(0);
        $number = $this->formatTxt(0, ['display' => \Magento\Framework\Currency::NO_SYMBOL]);
        return str_replace($this->trimUnicodeDirectionMark($number), '%s', $formatted);
    }
    public function getCurrencyRates($currency, $toCurrencies = null)
    {
        if ($currency instanceof \Magento\Directory\Model\Currency)
        {
            $currency = $currency->getCode();
        }
        $data = $this->_getResource()->getCurrencyRates($currency, $toCurrencies);
        return $data;
    }
    public function saveRates($rates)
    {
        $this->_getResource()->saveRates($rates);
        return $this;
    }
    private function trimUnicodeDirectionMark($string)
    {
        if (preg_match('/^(\x{200E}|\x{200F})/u', $string, $match))
        {
            $string = preg_replace('/^'.$match[1].'/u', '', $string);
        }
        return $string;
    }
}

Conclusion:

Hopefully, everyone was able to resolve the issue of Currency Symbol not Showing on the Product, Cart, and Checkout Page in Magento 2. If still, the problem persists, I can help you with it. You can catch me through the comment section.

Change the position of the currency symbol as in before the amount or after the amount in Magento 2 – Click Here

If you found the solution useful, share it with your friends and hit 5 stars. Stay in the loop with us for more Magento 2 solutions.

Happy Coding!

Exit mobile version