In Magento 2, you can retrieve a formatted price with currency using the following methods within your template files (.phtml) or blocks:
Method 1: Using the Object Manager (not recommended for production)
<?php
// Inject Object Manager at the top of your class or function
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// Load the price helper
$priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data');
// Your price value
$price = 100;
// Format price with currency
$formattedPrice = $priceHelper->currency($price, true, false);
echo $formattedPrice;
?>
Method 2: Using Dependency Injection (recommended approach)
<?php
// Inject these classes via constructor dependency injection
protected $_priceHelper;
public function __construct(
\Magento\Framework\Pricing\Helper\Data $priceHelper
) {
$this->_priceHelper = $priceHelper;
}
// Your method where you want to format the price
public function getFormattedPrice($price)
{
return $this->_priceHelper->currency($price, true, false);
}
// Example usage in a .phtml template file
echo $block->getFormattedPrice(100);
?>
Explanation:
- Object Manager Approach: Directly retrieves an instance of the
Magento\Framework\Pricing\Helper\Data
class using the Object Manager. This is generally discouraged for production code due to best practices favoring Dependency Injection. - Dependency Injection Approach: Utilizes Magento’s Dependency Injection framework to inject the
Magento\Framework\Pricing\Helper\Data
class into your block or template file. This is the recommended approach as it adheres to Magento’s best practices and ensures cleaner, more maintainable code.
Parameters of currency()
Method:
- First Parameter: The price to format.
- Second Parameter: Whether to include container span.
- Third Parameter: Whether to append currency sign.
Note:
- Ensure you adjust the context of where you use these methods based on whether you are in a block class or a template (.phtml) file.
- Always prefer the Dependency Injection approach for better code maintainability and compatibility with future Magento versions.
Using these methods, you can easily retrieve and display formatted prices with currency symbols in your Magento 2 store.