How to Set Price Format using JavaScript in Magento 2?

In a Magento 2 store, displaying prices in a proper format is necessary. The same format of pricing helps to offer a synchronized and seamless experience to the customers.

If you don't already have a singular price format, this article will help you with a guide on how to set price format using JavaScript.

How to Set Price Format Using Javascript in Magento 2?

Step 1.

You'd be required to use ‘Magento_Catalog/js/price-utils’ priceUtils Js Object in your javascript file to set format a price using javascript.

priceUtils.formatPrice(amount, priceFormat, showSign) can be used to format a price.

*amount = required field
priceFormat = Optional Object
showSign = Optional (Show sign like positive+/negative-)

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

    return {

        /**
         * Formats the price according to store
         *
         * @param {number} Price to be formatted
         * @return {string} Returns the formatted price
         */
        getFormattedPrice: function (price) {
            var priceFormat = {
                decimalSymbol: '.',
                groupLength: 3,
                groupSymbol: ",",
                integerRequired: false,
                pattern: "$%s",
                precision: 2,
                requiredPrecision: 2
            };

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

Step 2.

Now, all you need to do is call the function from the template or js file.

Whatever you put as the var amount, will be the price amount for your store. It can be changed as per the requirement. For instance, here we will keep it 199

var amount = 199;
getFormattedPrice(amount);

The Output will be $199. 

If you face any issues, feel free to reach out to our team of Magento 2 experts. We will be happy to help.

Also read: How to Get Formatted Price with Currency in Magento 2?