PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 23, 2022

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

 August 23, 2022     magento2, php     No comments   

Issue

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 , [ /* ... */ ] ); ?>

Solution

Working solution

Create an instance of the internal Amount\Base 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 Magento\Framework\Pricing\Amount\Base($price_incl_taxes, ['tax'=>$price_taxes]);

 ?>


Answered By - SimonBoh
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing