Sometimes during Magento 2 development, When you pass price value phtml to js at that time, you need to display price with currency from js or you may have some cases where you need to format price using javascript. Convert a plain number into a price format with a currency symbol using any one of the solutions given below.
Magento is able to operate with a variety of prices, taxes, and product types.
The following is a shortlist of Magento prices:
Magento represents these prices as price types (e.g. final price, minimum price, maximum price, regular price) and are separate from the actual price in the code. For example, Special Price is represented by the final price type in the code.
Magento handles taxes as price adjustments and has 3 generic types of taxes:
I am explaining the easiest way to do it.
You have to use ‘Magento_Catalog/js/price-utils‘ priceUtils Js Object in your javascript file to set format a price. then, you can just add getFormattedPrice() function in your file and add ‘Magento_Catalog/js/price-utils’ Js Object.
You also like to read: Add custom Js in Magento 2
priceUtils.formatPrice(price, priceFormat,showSign) has 3 arguments. You can check reference : vendor/magento/module-catalog/view/base/web/jsprice-utils.js
price:- Field is required
priceFormat:- Field is required
showSign:- Field is optional.It shows signs like (+) or (-) (positive+/negative-).
define([ 'ko', 'Magento_Catalog/js/price-utils' ], function ( ko, priceUtils ) { 'use strict'; return { /** * Formats the price with currency format * * @param {number} * @return {string} */ getFormattedPrice: function (price) { var priceFormat = { decimalSymbol: '.', groupLength: 3, groupSymbol: ",", integerRequired: false, pattern: "₹%s", precision: 2, requiredPrecision: 2 }; return priceUtils.formatPrice(price, priceFormat); } } });
You can call getFormattedPrice() function from template or js file with pass price.
var price=100;
getFormattedPrice(price);
You can change priceFormat object based on your requirement.
₹100.00
If you have any queries regarding this post, use the comment section below!
Happy Coding!