Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

229
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda