Magento 2 /价格和小计有4位小数,但增值税和总计有2位小数



我不得不将价格改为4位小数,这是可以的。然而,我有时在总数中有四舍五入的分,这是错误的。解释是所有的计算(小计、增值税和总计)都是在4位小数上,然后四舍五入到2位小数。在四舍五入的情况下,小计+增值税有时与总额相差1美分。

要解决这个问题,我需要:

  • 将产品价格保持在四位小数
  • 保持小计计算为4位小数,然后四舍五入为2位小数
  • 从这个四舍五入的小计计算增值税和总额,而不是从四位小数的小计。

但是我不知道该怎么做。我尝试了多种解决方案,没有任何工作:即使强制小计/增值税和节省,它似乎在其他地方再次计算,并且再次出现4个小数。

你能给我一些关于如何实现这一点的建议吗?谢谢!

我成功重写事件sales_quote_collect_totals_after

更新:这里是代码

Myvendor/Mymodule/etc/events.xml中的

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_quote_address_collect_totals_after">
<observer name="changeTotals" instance="MyvendorMymoduleObserverChangeTotals"/>
</event>
</config>

在Myvendor/Mymodule/Observer/changetotal .php中:

<?php
namespace MyvendorMymoduleObserver;
use PsrLogLoggerInterface as Logger;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkEventObserver;
class ChangeTotals implements ObserverInterface
{
/**
* @var Logger
*/
protected $_logger;

/**
* [__construct ]
* 
* @param Logger $logger
*/
public function __construct(
Logger $logger
) {
$this->_logger = $logger;
}
public function execute(Observer $observer)
{
/** @var MagentoQuoteModelQuoteAddressTotal */
$total = $observer->getData('total');

$subtotal = $total->getTotalAmount('subtotal');
$tax = $total->getTotalAmount('tax');
$grandTotal = $total->getGrandTotal();

/* $this->_logger->info('**** total_before **** ' , array($total->getData()));*/

/* the $total->getData() contains : 
[subtotal] => 0
[weee] => 0
[discount] => 0
[shipping] => 0
[shipping_discount] => 0
[tax] => 0
[discount_tax_compensation] => 0
[shipping_discount_tax_compensation] => 0
[extra_tax] => 0
[weee_tax] => 0*/

// i round tax to 2 decimals
$tax = round($tax,2);
$total->setTotalAmount('tax', $tax);
$total->setBaseTaxAmount($tax);

/* recalculate grandTotal */
$grandTotal = round($subtotal,2) + $tax + $total->getTotalAmount('discount') + $total->getShippingAmount()
+$total->getShippingDiscountAmount() + $total->getDiscountTaxCompensation() + $total->getShippingDiscountTaxCompensation() + $total->getExtraTax(), 2);
/* recalculate baseGrandTotal */
$baseGrandTotal = round($total->getBaseSubtotal(),2) + $tax + $total->getBaseDiscount() + $total->getBaseShippingAmount()
+ $total->getBaseShippingDiscountAmount() + $total->getBaseDiscountTaxCompensation() + $total->getBaseShippingDiscountTaxCompensation() + $total->getBaseExtraTax(), 2);
/* update totals */
$total->setGrandTotal($grandTotal);
/*$total->setBaseGrandTotal($baseGrandTotal);
/* $this->_logger->info('**** total_after **** ' , array($total->getData())); */
return $this;
}
}