Skip to content

Instantly share code, notes, and snippets.

@Dan0sz
Last active February 4, 2019 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dan0sz/8ed3b0890fa31bd4fad92747657f60a2 to your computer and use it in GitHub Desktop.
Save Dan0sz/8ed3b0890fa31bd4fad92747657f60a2 to your computer and use it in GitHub Desktop.
How to Format Prices using the Price Currency Interface in Magento 2
<?php
namespace Daan\CustomModule\Model; // Or Controller, or Plugin, or anything actually.
use Magento\Framework\Pricing\PriceCurrencyInterface as CurrencyInterface;
class Custom {
protected $currencyInterface;
public function __construct(
CurrencyInterface $currencyInterface
) {
$this->currencyInterface = $currencyInterface;
}
// Let's imagine I passed a valid $productCollection here.
public function getMyFormattedPrice( $productCollection ) {
$prices = [];
foreach ( $productCollection as $product ) {
$prices[] = $this->currencyInterface->format(
$product->getPrice(), // the price value.
false, // don't include the container span.
4 // default precision is two decimals, but I want 4 for some reason.
);
}
return $prices;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment