0

I have a variable $ customerProductPrices that contains data like this. enter image description here

How to format data (price, special_price, price_value, special_price_value) in a variable That I would get not just a number, but a formatted number with currency. Tentatively, the variable will contain not only 0 arrays, but more

2 Answers 2

2

as you haven't mentioned where the array variable $_customerProductPrices is from, whether its from a Block or from a ViewModel or in a template (.phtml file). As well as its also not mentioned how do you get this , whether through a repository method or from a collection or any other approach

Quick but Ugly

lets assume that its in a template file

in this case, loop through your array and get the variable formatted through this simple helper method

$priceFormatted = $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($_customerProductPrices[$keyindex]['price'], 2), true, false);

Better Approach

Inside your class where you get this variable, inject the interface Magento/Framework/Pricing/PriceCurrencyInterface and make use of the methods format or convertAndFormat

public function format(
        $amount,
        $includeContainer = true,
        $precision = self::DEFAULT_PRECISION,
        $scope = null,
        $currency = null
    );


    public function convertAndFormat(
        $amount,
        $includeContainer = true,
        $precision = self::DEFAULT_PRECISION,
        $scope = null,
        $currency = null
    );

These are the methods implemented by **Magento\Directory\Model\PriceCurrency**

you can also inject this class in your module class (Block / ViewModel) and make use of the format and convert methods in that concrete class

check the source here

0

You could try using what the classvendor/magento/module-directory/Model/PriceCurrency.php has to offer with its format() method. Check how this is used inside vendor/magento/module-customer-balance/Block/Adminhtml/Sales/Order/Create/Payment.php class.

1
  • What is the difference between convertAndFormat & format ?
    – devhs
    Commented Apr 5, 2021 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.