Some days before, I was working on a online ecommerce store. Fortunately it was a magento based ecommerce project. I was creating some new feature for the online store. I came across one minor problem. So the problem was if someone is changing the quantity amount, the product subtotal and total price should also be updated. Now it is very easy if we know the product unit price, we can multiply the quantity amount and hurry we got the subtotal price and accordingly we can calculate the total price also. But how to format the price, as this is a javascript code calculation. Ok here we go.
In magento we have a file named as js.js present inside “js/varien/” directory. In this file we have a method “formatCurrency”, which is meant for formating the price in magento store by javascript. It takes 3 parameters.
- price
- format[JSON (pattern, decimal, decimalsDelimeter, groupsDelimeter)]
- showPlus[ true (always show ‘+’or ‘-‘)- or –
false (never show ‘-‘ even if number is negative)
– or –
null (show ‘-‘ if number is negative)]
So in order to use this method we need to have the currency format in json. We can get the price format with the help of following code in magento.
Mage::helper('core')->jsonEncode(Mage::app()->getLocale()->getJsPriceFormat());
Here we can put the above code inside a method, which can be called in a .phtml file to print the price format in json.
Example :
public function getPriceFormat(){
return Mage::helper('core')->jsonEncode(
Mage::app()->getLocale()->getJsPriceFormat());
}
So in the .phtml file we can write it like
<script>var inst_price_format = <?php echo $this->getPriceFormat();?></script>
And now our job is done.
Finally we can call the formatCurrency() function by passing parameters as follows.
formatCurrency(105, inst_price_format)
This will give you the desired result.