Zum Hauptinhalt springen

Übersicht

Die Funktion createFormatter() gibt eine Intl.NumberFormat-Instanz zurück, die für die Währung Ihres Shops konfiguriert ist. Verwenden Sie sie, um Preise in Ihrem Storefront einheitlich darzustellen.

Den Formatter erhalten

const formatter = await komerza.createFormatter();
Gibt ein standardmäßiges JavaScript Intl.NumberFormat-Objekt zurück, das mit dem Währungscode Ihres Shops konfiguriert ist (z. B. USD, EUR, GBP).

Grundlegende Verwendung

const formatter = await komerza.createFormatter();

// Einen Preis formatieren
const price = formatter.format(29.99);
console.log(price); // "$29.99" (für USD-Shops)

Beispiele

const formatter = await komerza.createFormatter();

// Verschiedene Beträge
formatter.format(9.99); // "$9.99"
formatter.format(100); // "$100.00"
formatter.format(1499.5); // "$1,499.50"
formatter.format(0.99); // "$0.99"

// Funktioniert mit beliebigen Zahlen
formatter.format(29); // "$29.00"
formatter.format(29.9); // "$29.90"
formatter.format(29.999); // "$30.00" (gerundet)

Produktpreise anzeigen

async function produkte Anzeigen() {
  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)}`);
    });
  });
}

Preisspannen

„Ab $X” für Produkte mit mehreren Varianten anzeigen:
async function preisspanneAnzeigen(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)}`;
}

Warenkorbsumme

Warenkorb-Gesamtbeträge berechnen und formatieren:
async function getWarenkorbsumme() {
  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);
}

Formatter zwischenspeichern

Erstellen Sie den Formatter einmal und verwenden Sie ihn wieder, um unnötige API-Aufrufe zu vermeiden:
// Formatter global speichern
let currencyFormatter = null;

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

// In der gesamten App verwenden
async function preisFormatieren(amount) {
  const formatter = await getFormatter();
  return formatter.format(amount);
}

Intl.NumberFormat-Methoden

Da createFormatter() ein standardmäßiges Intl.NumberFormat zurückgibt, haben Sie Zugriff auf alle seine Methoden:

format()

Gibt eine formatierte Zeichenkette zurück:
formatter.format(1234.56); // "$1,234.56"

formatToParts()

Gibt ein Array von Teilen für benutzerdefiniertes Rendering zurück:
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" }
// ]

// Benutzerdefinierte Anzeige erstellen
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}`);

Währung nach Shop

Der Formatter verwendet automatisch die konfigurierte Währung Ihres Shops:
Shop-WährungBeispielausgabe
USD$29.99
EUR€29.99
GBP£29.99
JPY¥2,999
CADCA$29.99
AUDA$29.99

Vollständiges Beispiel

<!DOCTYPE html>
<html>
  <head>
    <title>Produkte</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() {
        // Formatter und Shop-Daten abrufen
        const [fmt, storeResponse] = await Promise.all([
          komerza.createFormatter(),
          komerza.getStore(),
        ]);

        formatter = fmt;

        if (!storeResponse.success) return;

        // Produkte mit formatierten Preisen anzeigen
        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})">
              In den Warenkorb
            </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();
        const count = komerza.getBasketItemCount();
        document.getElementById("cart-total").textContent =
          `${count} Artikel im Warenkorb`;
      }

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

Nächste Schritte

Shop-Informationen

Erfahren Sie mehr über andere Shop-Daten, die Sie abrufen können

Warenkorb-Verwaltung

Warenkorbpositionen verwalten