Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
How to display localized (best fit) units with Intl?

When working with dates it automatically localizes them, i.e. my local date would be YYYY-MM-DD while with en-US locale I would receive DD/MM/YY.

When working with length, area, weight, volume, temperature, time and their compound units like length-per-time I can't find a similar feature in Intl API. I've been searching specs and github for whole day, but the closest thing I found was https://github.com/tc39/ecma402/issues/32 :

var f = Intl.UnitFormat(navigator.languages, {
  units: {
    {type: 'length', unit: 'bestFit'},
  }
});
f.format(2048); // would return '2 km' in en-US

Which seems to be gone after merging into "Intl.NumberFormat rev. 2".

So is there a way to avoid mapping every existing locale with every existing unit like in this example?:

const format = unit => value =>
  new Intl.NumberFormat("en", {
    style: "unit",
    unit,
    notation: "compact",
    maximumSignificantDigits: 3
  })
  .format(value)


function fakeBestFit(value, locale) {
  // if US or any other imeprial system based locale
  if (locale || navigator.language === 'en-US') {
    const mile = 1609.34
    const yard = 0.9143977272588
    // const inch = ...
    // const foot = ...
    if (value >= mile) {
      return format("mile")(value / mile)
    } else if (value >= yard) {
      return format("yard")(value / yard)
    } else {
      // other units for locale i.e. inches and feet
    }
  } else {
    // for metric countries
    return format("meter")(value)
  }
}

console.log('expected: 1 m, received: ' + fakeBestFit(1))
console.log('expected: 1 km, received: ' + fakeBestFit(1000))
console.log('expected: 1 Mm, received: ' + fakeBestFit(1000000))
console.log('expected: 1 cm, received: ' + fakeBestFit(0.001))
console.log('expected: 1 mi, received: ' + fakeBestFit(1609.34, 'en-US'))
console.log('expected: 1 yd, received: ' + fakeBestFit(0.9143977272588, 'en-US'))

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda