Reputation: 7213
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
Reputation: 177860
You have THREE issues
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