9

In javascript I have calculated a number. Which I want to display as a price.

My JS file

define([
    'jquery'
], function ($) {
    "use strict";

    function irreleventCalculations() {
        // black magic here
        return 19.949999;
    }
    var price = irrelevenCalculation();

    jQuery('#myCustomPriceDiv').text(formatedPrice);

    return $;
});

How should I do this in Magento 2?

3
  • Can you please share your code?
    – Amit Bera
    Mar 29 '16 at 13:54
  • try using .toFixed(2) method. Ie formatedPrice = price.toFixed(2) Mar 29 '16 at 14:32
  • @R.S I want it to format the price according to the settings. So the correct symbol and some countries have more then two floats
    – janw
    Mar 29 '16 at 14:35
20

Take a look at shipping_method/price.js

define(
    [
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Catalog/js/price-utils'
    ],
    function ($,quote, priceUtils) {
        "use strict";
            ......
            formatedPrice = getFormattedPrice(price)

            getFormattedPrice: function (price) {
                //todo add format data
                return priceUtils.formatPrice(price, quote.getPriceFormat());
            }
        });
    }
);
4
  • That helped. I'll post my code in a seperate answer. But accept yours.
    – janw
    Mar 30 '16 at 7:25
  • 4
    This is working only on cart and checkout pages. On the other pages window.checkoutConfig is undefined and can't access quote object and throws an error: Uncaught TypeError: Cannot read property 'quoteData' of undefined at quote.js:13 May 26 '17 at 13:20
  • @MiroslavPetroff Did you find a simple solution for this? Other than writing own code to get the price format?
    – Alex
    Dec 10 '18 at 9:41
  • For those looking how to get the actual priceFormat object (depending of the store config): magento.stackexchange.com/a/151836/77158
    – nikoskip
    Nov 15 '19 at 3:54
6

Based on the answer of R.S

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

    function irreleventCalculations() {
        // black magic here
        return 19.949999;
    }
    var price = irrelevenCalculation();
    price = priceUtils.formatPrice(price);


    jQuery('#myCustomPriceDiv').text(formatedPrice);

    return $;
});
1
  • 1
    This seems to work only for non localized price formats.
    – Alex
    Dec 10 '18 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.