Sometimes during development in Magento 2, you may have some cases where you need to format price using javascript. 

In this article, we will show you how to Format Price using JavaScript in Magento 2

Format Price Using JavaScript

You can use  ‘Magento_Catalog/js/price-utils’ in your javascript file to format a price using javascript.

The code to format the price will be as follow: priceUtils.formatPrice(amount, priceFormat, showSign)

  • amount: this field is required
  • priceFormat: this object is optional
  • showSign:  this is optional. It shows signs like (+) or (-)

Example #1

define([
    'Magento_Catalog/js/price-utils'
], function (priceUtils) {
    'use strict';
 
    return { 
        /**
         * Formats the price
         *
         * @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);
        }
    }
});

Example #2 

define([
    'ko',
    'jquery',
    'Magento_Checkout/js/view/summary/abstract-total',
    'Magento_Checkout/js/model/quote',
    'Magento_Catalog/js/price-utils'
], function (ko, $, Component, quote, priceUtils) {
    'use strict';
     return Component.extend({
     /**
       * @return {*|String}
       */
     getFormattedPrice: function () {
        var price = 50; // your price value
        return priceUtils.formatPrice(price, quote.getBasePriceFormat());
      }
    });
});

Conclusion

We hope you find this guide to "Format Price using JavaScript in Magento 2" helpful. Feel free to share or leave a comment below. Your opinion is much appreciated!

If you're looking for experienced Magento 2 developers to customize your site, fix issues, develop custom solutions, maintain, or anything else, feel free to check on this collection of Quality Services For Magento 2, choose the service that best suits your needs, or contact us

Tags: magento-2-frontend-development