Magento 2 Format Price Value in Knockout Template – How to

checkoutknockoutjsmagento2

In Magento 2's checkout summary I managed to add price values to each "item in cart":

<span data-bind="text: $parent.price_incl_tax"></span>
<span data-bind="text: $parent.row_total_incl_tax"></span>

Unfortunately those are plain numbers and a debug shows that $parent does not contain pre-formatted price values:

{
  "item_id":134,
  "price":420.17,
  "base_price":420.17,
  "qty":1,
  "row_total":420.17,
  "base_row_total":420.17,
  "row_total_with_discount":0,
  "tax_amount":79.83,
  "base_tax_amount":79.83,
  "tax_percent":19,
  "discount_amount":0,
  "base_discount_amount":0,
  "discount_percent":0,
  "price_incl_tax":500,
  "base_price_incl_tax":500,
  "row_total_incl_tax":500,
  "base_row_total_incl_tax":500,
  "options":"[]",
  "weee_tax_applied_amount":null,
  "weee_tax_applied":null,
  "name":"My awesome product"
}

How could I format these as actual price values?

Best Answer

VendorName/ModuleName/view/frontend/requirejs-config.js


var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/view/summary/item/details': {
                'VendorName_ModuleName/js/mixin/details-mixin': true
            }
        }
    }
};

VendorName/ModuleName/view/frontend/web/js/mixin/details-mixin.js


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

    return function (target) {
        return target.extend({
            /**
             * @param {*} price
             * @return {*|String}
             */
            getFormattedPrice: function (price) {
                return priceUtils.formatPrice(price, quote.getPriceFormat());
            }
        });
    }
});

Now use :


<span data-bind="text: getFormattedPrice($parent.price_incl_tax)"></span>
<span data-bind="text: getFormattedPrice($parent.row_total_incl_tax)"></span>

Clear cache and deploy static content.

Related Topic