Format a Price Using Javascript(JS) in Magento 2 to display a price with proper formatting.
You have 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) 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); } } });
Call a function from a template or js file,
var amount = 99;
getFormattedPrice(amount);
You can change the priceFormat object based on your requirements.
Output:
$99.00