Get formatted price by currency code in magento2 – We all know that magento catalog product model provides method to get formatted product price but it gives price in current store currency.
So what if we need to get the product price formatted price in magento2 in any desired currency then you don’t need to worry about this. Here I am going to explain how to get formatted price in any desired currency rate.
Get formatted price by currency code in magento2:
It is very simple and easy to get the formatted price. You just only need to follow few easy steps and you will get the desired output. So here following the steps given below –
Step 1 : Create construct method in the class where you want to get the formatted price using the below code.
/** * @var \Magento\Framework\Pricing\PriceCurrencyInterface */ protected $_priceCurrency; /** * @param Context $context * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency * @param array $data */ public function __construct( Context $context, \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency, array $data = [] ) { $this->_priceCurrency = $priceCurrency; parent::__construct($context, $data); }
NOTE: Inject the depency (\Magento\Framework\Pricing\PriceCurrencyInterface) in the constructor as shown in the above code.
Step 2 : Create a formatted price method “getFormattedPrice” which accepts two arguments to get formatted price by currency code.
/** * Get formatted by price and currency * * @param $price * @param $currency * @return array || float */ public function getFormatedPrice($price, $currency) { $precision = 2, // for displaying price decimals 2 point return $this->_priceCurrency->format( $price, $includeContainer = true, $precision, $scope = null, $currency ); }
Here, in the first argument pass the amount or price that needs to be converted and in the second arguement you need to pass the Currency code for example : ‘USD’.
Parameters used in format function:
- Price: amount to be formatted
- includeContainer: this will add the span tag with class=”price” if set to true.
- precision: this tells the method about the number of digits to be considered after decimal
- scope : tells the scope of the store
- currency: this is the currency code in which you want the amount to be formatted (used for symbolising)
So If you call getFormatedPrice(100, ‘USD’) then it will return $100.00 value, so in this way you can get formatted price in desired currency.
You can also check :
https://webkul.com/blog/convert-price-current-currency-magento2/
Be the first to comment.