Custom price calculations

On your localized sites, prices may appear in different formats depending on the given country and currency. If your domestic site has custom JavaScript code that is doing dynamic calculation with prices extracted from the page, this code should be prepared to also handle prices in other formats and currencies than the one used on your domestic site. Otherwise, calculation can either fail with an error or produce incorrect results on your localized sites. Common places for this problem to appear are cross-sell and upsell popups or dynamic discount promotions, reading prices from the cart section of the page.

Most dynamic features on e-commerce websites are not extracting prices from the visible parts of the page, but use structured data in JSON format or else. These will not be affected by Glopal website localization.

In case you must do calculation based on extracted prices, there are two recommended ways for developers on how to avoid any potential problems:

  1. Expose source / unlocalized price

This option requires modification of site HTML template by adding source content price in additional price element attribute. This way source price is preserved in the attribute regardless of the visible price, which will be localized.

Note: Using this method you can make calculations using source price on every localized site.

See example below:

  • Add source content price in price element attribute

  • Query attribute value instead textContent when doing calculations

Javascript

const priceElement = document.querySelector('div[gp-unitprice]');
if (priceElement) {
  const priceAmount = priceElement.getAttribute('gp-unitprice');
  // priceAmount: 223.35
  ...
}

  1. Parse localized price

Glopal provides an easy interface to parse localized prices back to the numeric amount that can be used in calculations.

Note: Using this method you can make calculations using localized price on every localized site.

See example below:

  • Let’s assume we want to make calculations using the localized price:

  • We can write code to extract the price and parsing its value:

Javascript

const priceElement = document.querySelector('span.price');
if (priceElement) {
  const priceText = priceElement.textContent;
  const priceAmount = window.glopal
    ? glopal.engine.replacer.parseTargetCurrencyString(priceText)
    : parseFloat(priceText);
  // priceAmount: 1016.99
  ...
}

Last updated