10

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, 2016 at 13:54
  • try using .toFixed(2) method. Ie formatedPrice = price.toFixed(2) Mar 29, 2016 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, 2016 at 14:35

2 Answers 2

25

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, 2016 at 7:25
  • 7
    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, 2017 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, 2018 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, 2019 at 3:54
7

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, 2018 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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