Skip to content

Instantly share code, notes, and snippets.

@0-Sony
Created August 28, 2019 10:37
Show Gist options
  • Save 0-Sony/db3f5959c4932549056f7c0bfbc0f181 to your computer and use it in GitHub Desktop.
Save 0-Sony/db3f5959c4932549056f7c0bfbc0f181 to your computer and use it in GitHub Desktop.
Magento 2 : Change Price Format / Precision Currency
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Tax\Block\Item\Price\Renderer">
<plugin sortOrder="1" name="myCustomRenderer" type="MyNamespace\MyModule\Plugin\Block\Item\Price\RendererPlugin"/>
</type>
</config>
<?php
/**
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @author Phuong LE <sony@menincode.com> <@>
* @copyright Copyright (c) 2019 Menincode (http://www.menincode.com)
*/
namespace MyNamespace\MyModule\Plugin\Block\Item\Price;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\View\Element\Template\Context;
use Magento\Quote\Model\Quote\Item\AbstractItem as QuoteItem;
use Magento\Sales\Model\Order\Item as OrderItem;
use Magento\Tax\Helper\Data as TaxHelper;
class RendererPlugin extends \Magento\Tax\Block\Item\Price\Renderer
{
/**
* @var PriceCurrencyInterface
*/
protected $priceCurrency;
/**
* RendererPlugin constructor.
* @param Context $context
* @param TaxHelper $taxHelper
* @param PriceCurrencyInterface $priceCurrency
* @param array $data
*/
public function __construct(
Context $context,
TaxHelper $taxHelper,
PriceCurrencyInterface $priceCurrency,
array $data = []
)
{
parent::__construct($context, $taxHelper, $priceCurrency, $data);
}
/**
* Change Precision Currency for cart / checkout
* @param \Magento\Tax\Block\Item\Price\Renderer $subject
* @param callable $proceed
* @param $price
* @return float|string
*/
public function aroundFormatPrice(\Magento\Tax\Block\Item\Price\Renderer $subject, callable $proceed, $price)
{
$precisionCurrency = PriceCurrencyInterface::DEFAULT_PRECISION; // Default precision is 2. Here you can set 0 if no decimal wanted
$item = $subject->getItem();
if ($item instanceof QuoteItem) {
return $subject->priceCurrency->format(
$price,
true,
$precisionCurrency,
$item->getStore()
);
} elseif ($item instanceof OrderItem) {
return $item->getOrder()->formatPrice($price);
} else {
return $item->getOrderItem()->getOrder()->formatPrice($price);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment