Google logo
4.9 on Google
Get a free Magento audit

Recommendations on page speed, accessibility issues, and real user experience data

Skip to main article

How to format numbers to prices in Magento 2

Looking for a how to convert raw numbers to format price in M2, look no further!

How to format numbers to prices in Magento 2
10 mins

Mike is our Technical Director who has worked on eCommerce projects since 2014 and has been with Develo since 2015. He became certified in Adobe Commerce in 2023. Mike’s favourite aspect of web development is tackling intricate eCommerce challenges with the bespoke platform Magento/Hyvä, and he tells us his best achievement from working at Develo is fostering a culture of growth and innovation within our team. Outside of work, he can be found spending time with his family, baking and walking his dogs.

Develo is a leading Magento agency and eCommerce web development company based in Birmingham, in the UK, serving clients globally since 2010.

In Magento 2 you may need to convert raw numbers into the formatted price.


Let's break down how to achieve this in PHP!

In a PHTML template:

$priceHelper = $this->helper('Magento\Framework\Pricing\Helper\Data');
$rawPrice = 123;
$formattedPrice = $priceHelper->currency($rawPrice);

echo $formattedPrice; // (outputs: <span class="price">£123.00</span>)


In a controller:

class Example
{
   protected $priceHelper;
  
   public function __construct(\Magento\Framework\Pricing\Helper\Data $priceHelper)
   {
       $this->priceHelper = $priceHelper;
   }
}


Use this when you want to format the price throughout your controller.

$this->priceHelper->currency($price)


More details:

The priceHelper->currency() function accepts the following parameters:
$value (required)
$format (optional, default: true)
$includeContainer (optional, default: true)

Setting the $includeContainer to false will output the formatted price without html: £123.00, setting the parameter to true, will output your price wrapped in html that is consistent with where the price is rendered across Magento:

<span class="price">£123.00</span>

Last updated: April 16, 2024

Why not take a look at our other code snippets?

Learn with us

Latest learning resources

Practical ideas, helpful platform tips, and smart strategies to help your eCommerce store thrive.