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!

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.


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>

Why not take a look at our other code snippets?





Ready to start your next project?

See how we can help you accelerate your business