Crow
Crow

Reputation: 7213

Intl NumberFormat currency per unit

I need to format prices per unit. i.e. 2 336 €/m², $2.336/ac.

Intl.NumberFormat works with currency OR unit style. Can't use both.

How shall one format currency per unit?

Upvotes: 1

Views: 1942

Answers (1)

mplungjan
mplungjan

Reputation: 177860

You have THREE issues

  1. Intl numberformat for currency
  2. Intl numberformat for units
  3. Using units that are not supported: Exponent notation for Intl.NumberFormat

const sups = ["²", "³"];
const currencyPerUnit = (amount, unit, sup, noDec, locale = "en-US", currency = "USD", ) => {
  const numberWithCurrency = (amount).toLocaleString(locale, {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: noDec ? 0 : 2,
  });
  const units = (amount).toLocaleString('fr-FR', {
    style: 'unit',
    unit: unit,
    unitDisplay: 'short'
  }).split(/\s+/).pop();
  return `${numberWithCurrency}/${units}${sup ? sups[sup-2] : ""}`;
};

console.log(currencyPerUnit(1234, "meter", 2, true, "fr-FR", "EUR")); // Euro per m² in French
console.log(currencyPerUnit(1234.14, "acre", 0, false)); // USD per acre
console.log(currencyPerUnit(1234.14, "acre", 2, true, "fr-FR", "EUR")); // Eure per square acre in French

Upvotes: 3

Related Questions