Magento, Magento 2

How to Set Price Format using JavaScript in Magento 2

How to Set Price Format using JavaScript in Magento 2

In this tutorial, Today I will explain to how to set price format using JavaScript in Magento 2. Generally, when you pass custom price value from phtml file to JS file at that time, You need to display price with currency from JS. You need to follow the below steps to display currency symbol with price from Javascript.

You may also like this :

For that, You need to use ‘Magento_Catalog/js/price-utils’ in your JavaScript file. Add this below code in your JavaScript file. If you created already JavaScript file then, you can just add getFormattedPrice() function in your file and add ‘Magento_Catalog/js/price-utils’ Js.

/**
 * Created By : Rohan Hapani
 */


define([
    'ko',
    'Magento_Catalog/js/price-utils'
], function (
    ko,
    priceUtils
) {
    'use strict';

    return {

        /**
         * Formats the price with currency format
         *
         * @param {number} price
         * @return {string}
         */
        getFormattedPrice: function (price) {
            var priceFormat = {
                decimalSymbol: '.',
                groupLength: 3,
                groupSymbol: ",",
                integerRequired: false,
                pattern: "$%s",
                precision: 2,
                requiredPrecision: 2
            };

            return priceUtils.formatPrice(price, priceFormat);
        }
    }
});

priceUtils.formatPrice(amount, format, isShowSign) has 3 arguments. You can check in this file for reference : vendor/magento/module-catalog/view/base/web/jsprice-utils.js

Now, You can call getFormattedPrice() function with pass price. For ex : getFormattedPrice(5); You can also customize this function based on your requirements.

Output : $5.00

I hope this blog is easy to understand about how to set price format using JavaScript in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,