Skip to content
Advertisement

How can I make an amount instance from float in Magento 2?

There is a customly generated float called $price, which should be displayed as the price for a product in a product list in Magento 2. For displaying a price with taxes excluded/included, the method renderAmount is used. The method requires one parameter. The parameter is called $amount and how I see it, it needs to be of the type amount.

How can I convert (float) $price to (amount) $amount to be able to use the method renderAmount correctly?

In other words: What would the imaginary function convertFloatToAmount do?

<?php
    // ...
    $price = 100.00;
    $amount = convertFloatToAmount( $price );
 ?>
<?= $block->renderAmount( $amount , [ /* ... */ ] ); ?>

Advertisement

Answer

Working solution

Create an instance of the internal AmountBase class.

To make this work it is required to have the price incl. taxes and the price taxes.

Hint: If you don’t know these, you might be able to calculate them by your existing values.

<?php

  // Define price incl. taxes
  $price_incl_taxes = 120.00;

  // Define the price taxes
  $price_taxes = 20.00;

  // If you need to know the price excl. taxes (== 100.00 in this example)
  /* $price_excl_taxes = $price_incl_taxes - $price_taxes; */

  // Create (amount) $amount
  $amount = new MagentoFrameworkPricingAmountBase($price_incl_taxes, ['tax'=>$price_taxes]);

 ?>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement