Ir al contenido
Español

Guía de formatos: números, fechas y moneda

Formateador

Escribe un valor. Cada fila es un formato, en los cuatro idiomas.

Elige un tipo de valor y escribe uno. La tabla muestra cada formato en inglés, chino simplificado, español y japonés, con la regla de cada formato bajo su nombre.

Número
FormatoEnglish简体中文Español日本語
AgrupadoHasta 2 decimales, sin ceros finales
FijoDinero y columnas comparadas
CompactoEspacios estrechos; valor completo al pasar

Números en columnas

Cifras tabulares, alineadas a la derecha. Las flechas dan el sentido.

Regla: Cifras tabulares
PedidoImporteCambio
#1042
#1043
#1044
#1045

La flecha da el sentido. El color sigue al mercado.

Tiempo relativo y zonas

Lo reciente en palabras, lo antiguo como fecha. Nombra la zona cuando importa.

  • English
  • 简体中文
  • Español
  • 日本語
Llamada de lanzamiento

Tu hora

  • Singapur
  • Tokio
  • Madrid
  • Nueva York

Enmascarado

Tres niveles. Se enmascara en el servidor.

Nombre
L*** P.
Teléfono
612**5678
Correo
j***@mail.com
Tarjeta
•••• 4242
Documento
12***678Z

El navegador nunca recibe lo que el nivel oculta. Mostrarlo pide verificar y queda registrado.

Vacío y carga

Un guion si se desconoce, una barra mientras carga, 0 solo si es cero.

Ingresos
Pedidos
Conversión
Ingresos—Pedidos—Conversión—
Sí Un guion si se desconoce; 0 solo si es un cero real.
IngresosNaNPedidosundefinedConversión$0.00
No Se cuelan valores en bruto: NaN, undefined, un 0 falso.

El módulo

Un módulo sin dependencias. Cada plan lo lleva como specs/format.js.

// LayQ format: every value on screen goes through here (specs/design.md, "Data formats"). Only Intl.
// A missing or unreadable value gives EMPTY, never NaN or undefined.
export const EMPTY = '—'

const missing = (v) => v == null || v === '' || (typeof v === 'number' && !Number.isFinite(v))
const toDate = (v) => (missing(v) || isNaN(new Date(v)) ? null : new Date(v))
const num = (v, locale, o) => (missing(v) ? EMPTY : new Intl.NumberFormat(locale, o).format(v))
const dt = (v, locale, o) => (toDate(v) ? new Intl.DateTimeFormat(locale, o).format(toDate(v)) : EMPTY)
const cycle = (hour12) => (hour12 ? 'h12' : 'h23')

export const number = (v, locale, { decimals = 2, fixed } = {}) => num(v, locale, { maximumFractionDigits: decimals, minimumFractionDigits: fixed ? decimals : 0 })
export const compact = (v, locale) => num(v, locale, { notation: 'compact', maximumFractionDigits: 1 })
export const percent = (ratio, locale) => num(ratio, locale, { style: 'percent', maximumFractionDigits: 1 })

// `direction` picks the colour, which depends on the market.
export function change(ratio, locale) {
  if (missing(ratio)) return { text: EMPTY, direction: 'none' }
  const step = Math.round(ratio * 1000)
  const direction = step > 0 ? 'up' : step < 0 ? 'down' : 'flat'
  return { text: { up: '▲ ', down: '▼ ', flat: '' }[direction] + num(ratio, locale, { style: 'percent', maximumFractionDigits: 1, signDisplay: 'exceptZero' }), direction }
}

// `minor`: in cents. `display`: 'symbol' or 'code'.
export function money(amount, currency, locale, { minor, display = 'symbol', compact } = {}) {
  if (missing(amount) || !currency) return EMPTY
  const digits = new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits
  const o = { style: 'currency', currency, currencyDisplay: display, ...(compact && { notation: 'compact', maximumFractionDigits: 1 }) }
  return num(minor ? amount / 10 ** digits : amount, locale, o)
}

// style: 'short' in tables, 'medium', 'long' in documents.
export const date = (v, locale, { style = 'medium', timeZone } = {}) => dt(v, locale, { dateStyle: style, timeZone })
export const time = (v, locale, { hour12, timeZone, zone } = {}) => dt(v, locale, { hour: '2-digit', minute: '2-digit', hourCycle: cycle(hour12), timeZone, timeZoneName: zone ? 'short' : undefined })
export function dateTime(v, locale, { style = 'medium', hour12, timeZone, zone } = {}) {
  const text = dt(v, locale, { dateStyle: style, timeStyle: 'short', hourCycle: cycle(hour12), timeZone })
  return zone && toDate(v) ? text + ' ' + new Intl.DateTimeFormat(locale, { timeZoneName: 'short', timeZone }).formatToParts(toDate(v)).at(-1).value : text
}
export const dateRange = (a, b, locale, { style = 'medium', timeZone } = {}) =>
  toDate(a) && toDate(b) ? new Intl.DateTimeFormat(locale, { dateStyle: style, timeZone }).formatRange(toDate(a), toDate(b)) : EMPTY

// [below this age in seconds, unit, seconds per unit]; past a week, the date.
export const relativeBands = [
  [60, 'now'],
  [3600, 'minute', 60],
  [86400, 'hour', 3600],
  [604800, 'day', 86400],
]
export function relative(v, locale, { now = Date.now() } = {}) {
  if (!toDate(v)) return EMPTY
  const s = (toDate(v) - now) / 1000
  const [, unit, size] = relativeBands.find(([below]) => Math.abs(s) < below) ?? []
  const words = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
  return !unit ? date(v, locale) : size ? words.format(Math.trunc(s / size), unit) : words.format(0, 'second')
}

// 1h 5m; style 'clock' (1:05:09) for media and timers.
export function duration(seconds, locale, { style } = {}) {
  if (missing(seconds)) return EMPTY
  const all = Math.max(0, Math.round(seconds))
  const [h, m, s] = [Math.floor(all / 3600), Math.floor(all / 60) % 60, all % 60]
  const two = (n) => String(n).padStart(2, '0')
  if (style === 'clock') return (h ? h + ':' + two(m) : m) + ':' + two(s)
  const unit = (n, u) => num(n, locale, { style: 'unit', unit: u, unitDisplay: 'narrow' })
  return (h ? [unit(h, 'hour'), m && unit(m, 'minute')] : m ? [unit(m, 'minute'), s && unit(s, 'second')] : [unit(s, 'second')]).filter(Boolean).join(' ')
}

export function bytes(v, locale) {
  if (missing(v) || v < 0) return EMPTY
  if (v < 1000) return number(v, locale) + ' B'
  const step = Math.min(4, Math.floor(Math.log10(v) / 3))
  const n = v / 1000 ** step
  return num(n, locale, { style: 'unit', unit: [, 'kilobyte', 'megabyte', 'gigabyte', 'terabyte'][step], maximumFractionDigits: n < 10 ? 1 : 0 })
}