Skip to main content

Overview

The createFormatter() function returns an Intl.NumberFormat instance configured for your store’s currency. Use it to display prices consistently throughout your storefront.

Getting the Formatter

const formatter = await komerza.createFormatter();
Returns a standard JavaScript Intl.NumberFormat object configured with your store’s currency code (e.g., USD, EUR, GBP).

Basic Usage

const formatter = await komerza.createFormatter();

// Format a price
const price = formatter.format(29.99);
console.log(price); // "$29.99" (for USD stores)

Examples

const formatter = await komerza.createFormatter();

// Different amounts
formatter.format(9.99); // "$9.99"
formatter.format(100); // "$100.00"
formatter.format(1499.5); // "$1,499.50"
formatter.format(0.99); // "$0.99"

// Works with any number
formatter.format(29); // "$29.00"
formatter.format(29.9); // "$29.90"
formatter.format(29.999); // "$30.00" (rounds)

Display Product Prices

async function displayProducts() {
  const [storeResponse, formatter] = await Promise.all([
    komerza.getStore(),
    komerza.createFormatter(),
  ]);

  if (!storeResponse.success) return;

  storeResponse.data.products.forEach((product) => {
    product.variants.forEach((variant) => {
      console.log(`${variant.name}: ${formatter.format(variant.cost)}`);
    });
  });
}

Price Ranges

Display “From $X” for products with multiple variants:
async function displayPriceRange(product) {
  const formatter = await komerza.createFormatter();

  const prices = product.variants.map((v) => v.cost);
  const minPrice = Math.min(...prices);
  const maxPrice = Math.max(...prices);

  if (minPrice === maxPrice) {
    return formatter.format(minPrice);
  }

  return `${formatter.format(minPrice)} - ${formatter.format(maxPrice)}`;
}

Cart Total

Calculate and format basket totals:
async function getCartTotal() {
  const [storeResponse, formatter] = await Promise.all([
    komerza.getStore(),
    komerza.createFormatter(),
  ]);

  if (!storeResponse.success) return null;

  const basket = komerza.getBasket();
  const products = storeResponse.data.products;

  let total = 0;

  basket.forEach((item) => {
    const product = products.find((p) => p.id === item.productId);
    if (!product) return;

    const variant = product.variants.find((v) => v.id === item.variantId);
    if (!variant) return;

    total += variant.cost * item.quantity;
  });

  return formatter.format(total);
}

Caching the Formatter

Create the formatter once and reuse it to avoid unnecessary API calls:
// Store formatter globally
let currencyFormatter = null;

async function getFormatter() {
  if (!currencyFormatter) {
    currencyFormatter = await komerza.createFormatter();
  }
  return currencyFormatter;
}

// Use throughout your app
async function formatPrice(amount) {
  const formatter = await getFormatter();
  return formatter.format(amount);
}

Intl.NumberFormat Methods

Since createFormatter() returns a standard Intl.NumberFormat, you have access to all its methods:

format()

Returns a formatted string:
formatter.format(1234.56); // "$1,234.56"

formatToParts()

Returns an array of parts for custom rendering:
const parts = formatter.formatToParts(1234.56);
// [
//   { type: "currency", value: "$" },
//   { type: "integer", value: "1" },
//   { type: "group", value: "," },
//   { type: "integer", value: "234" },
//   { type: "decimal", value: "." },
//   { type: "fraction", value: "56" }
// ]

// Build custom display
const integer = parts
  .filter((p) => p.type === "integer" || p.type === "group")
  .map((p) => p.value)
  .join("");

const fraction = parts.find((p) => p.type === "fraction")?.value || "00";

console.log(`$${integer}.${fraction}`);

Currency by Store

The formatter automatically uses your store’s configured currency:
Store CurrencyExample Output
USD$29.99
EUR€29.99
GBP£29.99
JPY¥2,999
CADCA$29.99
AUDA$29.99

Complete Example

<!DOCTYPE html>
<html>
  <head>
    <title>Products</title>
    <script src="https://cdn.komerza.com/komerza.min.js"></script>
  </head>
  <body>
    <div id="products"></div>
    <div id="cart-total"></div>

    <script>
      komerza.init("your-store-id");

      let formatter;

      async function init() {
        // Get formatter and store data
        const [fmt, storeResponse] = await Promise.all([
          komerza.createFormatter(),
          komerza.getStore(),
        ]);

        formatter = fmt;

        if (!storeResponse.success) return;

        // Display products with formatted prices
        const html = storeResponse.data.products
          .map((product) => {
            const variant = product.variants[0];
            const price = formatter.format(variant.cost);

            return `
          <div class="product">
            <h3>${product.name}</h3>
            <p class="price">${price}</p>
            <button onclick="addToCart('${product.id}', '${variant.id}', ${variant.cost})">
              Add to Cart
            </button>
          </div>
        `;
          })
          .join("");

        document.getElementById("products").innerHTML = html;
      }

      function addToCart(productId, variantId, cost) {
        komerza.addToBasket(productId, variantId, 1);
        updateCartTotal();
      }

      function updateCartTotal() {
        const basket = komerza.getBasket();
        // Calculate total (simplified - assumes you track costs)
        const count = komerza.getBasketItemCount();
        document.getElementById(
          "cart-total"
        ).textContent = `${count} items in cart`;
      }

      init();
    </script>
  </body>
</html>

Next Steps