Domanda

Magento 2 returns regular price differently from special and final price. Expected result:

$product->getPrice(); // 89,95
$product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); // 89,95
$product->getSpecialPrice(); // 49,95
$product->getPriceInfo()->getPrice('special_price')->getAmount()->getValue(); // 49,95
$product->getFinalPrice(); // 49,95
$product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); // 49,95

Given result:

$product->getPrice(); // 89,95
$product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(); // 89,95
$product->getSpecialPrice(); // 49
$product->getPriceInfo()->getPrice('special_price')->getAmount()->getValue(); // 49
$product->getFinalPrice(); // 49
$product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(); // 49

Somehow the special and final prices get returned without decimals. I tried al kind of things with different helpers (like the taxhelper etc.), but no success. Why does Magento 2.3 keep returning the special price without decimals?

EDIT: And if this is normal behaviour, what would be the proper way to get the special and final price in my module without currency symbols etc. but including tax?

È stato utile?

Soluzione

If you look following class:

vendor/magento/module-catalog/Pricing/Price/SpecialPrice.php

/**
 * Returns special price
 *
 * @return float
 */
public function getSpecialPrice()
{
    $specialPrice = $this->product->getSpecialPrice();
    if ($specialPrice !== null && $specialPrice !== false && !$this->isPercentageDiscount()) {
        $specialPrice = $this->priceCurrency->convertAndRound($specialPrice);
    }
    return $specialPrice;
}

Actually following line format price:

$this->priceCurrency->convertAndRound($specialPrice)

Now go to the following class:

vendor/magento/module-directory/Model/PriceCurrency.php

And check the following code

/**
 * Round price with precision
 *
 * @param float $price
 * @param int $precision
 * @return float
 */
public function roundPrice($price, $precision = self::DEFAULT_PRECISION)
{
    return round($price, $precision);
}

Check documentation for round as well

Here is the sample example:

<?php

echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top