Documentation Index Fetch the complete documentation index at: https://docs.komerza.com/llms.txt
Use this file to discover all available pages before exploring further.
Descripción general
La función createFormatter() devuelve una instancia de Intl.NumberFormat configurada para la moneda de tu tienda. Úsala para mostrar precios de forma consistente en tu tienda.
const formatter = await komerza . createFormatter ();
Devuelve un objeto JavaScript estándar Intl.NumberFormat configurado con el código de moneda de tu tienda (p. ej., USD, EUR, GBP).
Uso básico
const formatter = await komerza . createFormatter ();
// Formatear un precio
const price = formatter . format ( 29.99 );
console . log ( price ); // "$29.99" (para tiendas en USD)
Ejemplos
const formatter = await komerza . createFormatter ();
// Diferentes importes
formatter . format ( 9.99 ); // "$9.99"
formatter . format ( 100 ); // "$100.00"
formatter . format ( 1499.5 ); // "$1,499.50"
formatter . format ( 0.99 ); // "$0.99"
// Funciona con cualquier número
formatter . format ( 29 ); // "$29.00"
formatter . format ( 29.9 ); // "$29.90"
formatter . format ( 29.999 ); // "$30.00" (redondeado)
Mostrar precios de productos
async function mostrarProductos () {
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 ) } ` );
});
});
}
Rangos de precios
Muestra “Desde $X” para productos con múltiples variantes:
async function mostrarRangoDePrecio ( 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 ) } ` ;
}
Total del carrito
Calcula y formatea los totales del carrito:
async function getTotalCarrito () {
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 );
}
Crea el formateador una vez y reutilízalo para evitar llamadas API innecesarias:
// Guardar el formateador globalmente
let currencyFormatter = null ;
async function getFormatter () {
if ( ! currencyFormatter ) {
currencyFormatter = await komerza . createFormatter ();
}
return currencyFormatter ;
}
// Usar en toda tu aplicación
async function formatearPrecio ( amount ) {
const formatter = await getFormatter ();
return formatter . format ( amount );
}
Como createFormatter() devuelve un Intl.NumberFormat estándar, tienes acceso a todos sus métodos:
Devuelve una cadena formateada:
formatter . format ( 1234.56 ); // "$1,234.56"
Devuelve un array de partes para renderizado personalizado:
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" }
// ]
// Construir visualización personalizada
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 } ` );
Moneda por tienda
El formateador usa automáticamente la moneda configurada en tu tienda:
Moneda de la tienda Ejemplo de salida USD $29.99 EUR €29.99 GBP £29.99 JPY ¥2,999 CAD CA$29.99 AUD A$29.99
Ejemplo completo
<! DOCTYPE html >
< html >
< head >
< title > Productos </ 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 () {
// Obtener formateador y datos de la tienda
const [ fmt , storeResponse ] = await Promise . all ([
komerza . createFormatter (),
komerza . getStore (),
]);
formatter = fmt ;
if ( ! storeResponse . success ) return ;
// Mostrar productos con precios formateados
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 } )">
Añadir al carrito
</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 } artículo(s) en el carrito` ;
}
init ();
</ script >
</ body >
</ html >
Próximos pasos
Información de la tienda Conoce otros datos de la tienda que puedes obtener
Gestión del carrito Gestiona los artículos del carrito