How can I show the amount saved in Magento 2?

Viewed 2574

I am trying to display amount saved on the catalog page for a Magento 2.0.2 website. However I'm not getting the calculation result displayed. I just get an empty space. I am editing the final_price.phtml in my theme file.

I didn't find any information in google as most results are for related to Magento 1 and the codes are throwing errors.

This is what my code looks like in the section which I am trying to do the calculations.

<span class="special-price"><span class="only-text">Only: </span>
    <?php echo $block->renderAmount($finalPriceModel->getAmount(), [
        'display_label'     => __('Special Price'),
        'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
        'price_type'        => 'finalPrice',
        'include_container' => true,
        'schema' => $schema
    ]); ?>
</span>
<br>
<span class="old-price"><span class="rrp-text">RRP: </span>
    <?php echo $block->renderAmount($priceModel->getAmount(), [
        'display_label'     => __('Regular Price'),
        'price_id'          => $block->getPriceId('old-price-' . $idSuffix),
        'price_type'        => 'oldPrice',
        'include_container' => true,
        'skip_adjustments'  => true
    ]); ?>
</span>
<span class="saving-price"><span class="saving-text">Saving: </span>
<?php
$wasPrice = $block->renderAmount($priceModel->getAmount(), []);
$nowPrice = $block->renderAmount($finalPriceModel->getAmount(), []);
  if ($nowPrice < $wasPrice){
    $saving = $wasPrice - $nowPrice; 
    echo $saving;
  }
?>
</span>
3 Answers

instead of using

$wasPrice = $block->renderAmount($priceModel->getAmount(), []);
$nowPrice = $block->renderAmount($finalPriceModel->getAmount(), []);

you should use

$wasPrice = $priceModel->getValue();
$nowPrice = $finalPriceModel->getValue();

$priceModel and $finalPriceModel refer to /** @var \Magento\Framework\Pricing\Price\PriceInterface $priceModel */ as you can see in line 17 in your final_price.phtml

then inside of the PriceInterface.php we'll see that getAmount() returns an object while getValue() just returns a number.

/**
 * Get price value
 *
 * @return float
 */
public function getValue();

/**
 * Get Price Amount object
 *
 * @return AmountInterface
 */
public function getAmount();
Related