How To

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

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!

Click to rate this post!
[Total: 6 Average: 4.3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

12 hours ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

13 hours ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

1 day ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

3 days ago

HYVĂ„ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We're thrilled to announce the release of Hyvä Themes 1.3.6 and 1.3.7! These latest updates…

3 days ago

How Modern E-Commerce Platforms Leverage Docker & Kubernetes for Scalability

Your e-commerce platform is surging - orders are rolling in, traffic spikes are becoming the…

4 days ago