October 7, 2021
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)
$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
