Hello Magento Lovers,

 

It's pretty easy to convert a number into a currency format. We can use a quick way by using Object Manager but we should not use it and maintain dependency


I will show you both methods by this post.

 

1) Convert a number to currency format using Object Manager

 

    <?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$priceHelper = $objectManager->create('Magento\Framework\Pricing\PriceCurrencyInterface');
$price =  1500.50; //Your Custom Price
echo $formattedPrice = $priceHelper->convertAndFormat($price);
//Output: $1500.50 (Symbol depends on currency setup of Magento)
echo $formattedPrice = $priceHelper->round($price);
//Output: 1500.5
echo $formattedPrice = $priceHelper->getCurrencySymbol();
//Output: $ (depends on currency setup)
?>
	

 

This is the shortest method however we should not use it. 

 

2) Pass PriceCurrencyInterface as a dependency inside the block, helper, controller, etc.

I have used helper to convert number into currency.

    <?php

namespace Magefever\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Pricing\PriceCurrencyInterface as PriceCurrency;

class Data extends AbstractHelper
{
    /**
     * @var Magento\Framework\Pricing\PriceCurrencyInterface
     */
    protected $priceCurrency;

    /**
     * @param Context $context
     * @param PriceCurrency $PriceCurrency
     */
    public function __construct(
        Context $context,
        PriceCurrency $priceCurrency
    ) {
        parent::__construct($context);
        $this->priceCurrency = $priceCurrency;
    }

    /**
     * @param double price
     * @return string
     */
    public function getCurrencyFormat($price){
        return $this->priceCurrency->format($price, true, 2);   
    }

    /**
     * @param double price
     * @return double
     */
    public function getRoundedPrice($price){
        return $this->priceCurrency->round($price);
    }


    /**
     * @return string
     */
    public function getCurrencySymbol(){
        return $this->priceCurrency->getCurrencySymbol();   
    }
}
	

 

We can inject this helper in phtml to get currency format:

    <?php
$priceCurrencyHelper = $this->helper('\Magefever\Module\Helper\Data');

echo $priceCurrencyHelper->getCurrencyFormat(1500);
//Output: $1500 (Symbol depends on currency setup of Magento)
echo $priceCurrencyHelper->getRoundedPrice(1500.500);
// Output: 1500.5
echo $priceCurrencyHelper->getCurrencySymbol();
//Output: $ (depends on currency setup)

	

 

Thank you for visiting our blog, please write your review so we can improve our content and service.