How to convert number into currency format in magento2

In magento 2, there are no 'core' module. You can get this by following way inside view file(.phtml)

$this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format(50,2),true,false);

What you want to do is to inject the "PriceCurrencyInterface" in the Block of the template file that you wish to use this in.

template.phtml

<div><?= $block->getFormatedPrice('342.4345') ?>

Item.php (Block Class of the above template... whatever that might be)

<?php
namespace \Whatever

use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\View\Element\Template;

class Item extends Template
{
    /** @var PriceCurrencyInterface $priceCurrency */
    protected $priceCurrency;

    public function __construct(
        Template\Context $context,
        PriceCurrencyInterface $priceCurrency,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->priceCurrency = $priceCurrency;
    }

    /**
     * Function getFormatedPrice
     *
     * @param float $price
     *
     * @return string
     */
    public function getFormatedPrice($amount)
    {
        return $this->priceCurrency->convertAndFormat($amount);
    }

This has the added benefit of displaying the correct format based on current store locale. It also offers other methods that might be helpful, check them out...

Make sure to check the method signature since you can configure the result you want to display such as the container and the precision.

priceCurrency->convertAndFormat($amount, $includeContainer, $precision)

Cheers!


First of all do not do currency formatting inside your view (.phtml) files, use helpers or blocks or combination of both.

The accepted answer uses number_format function which should not be used at all, at least I wouldn't go with that approach.

You can try using a model:

Model of type Magento\Directory\Model\Currency. Function format() as it's the one responsible for decimal places and formatting.

Example assuming variables $model and $product have been instantiated:

$model->format($product->getPrice(), array('symbol' => ''), false, false)

2 decimal places for formatting without $ dollar next to the amount. Pass empty array() if you want store currency appended to your amount.

Tags:

Magento2