ecma402
ecma402 copied to clipboard
Design for currency and unit inputs that carry their values
Rather than setting the unit/currency in the constructor, should it also be carried in the type being formatted?
Might be wanted by Intl.MessageFormat.
CC @eemeli
@sffc: in the constructor of what?
A currency value should carry its currency code (and not just a number) around. A unit amount should likewise not forget it's unit.
Currently one needs to set the currency or unit in the constructor of Intl.NumberFormat, and the .format() function takes only the number. The ask is for the unit and currency to be passable directly into .format().
For context, the MF2 spec currently includes this for its :number options:
The following values for the option
styleare not part of the default registry. Implementations SHOULD avoid creating options that conflict with these, but are encouraged to track development of these options during Tech Preview:
currencyunit
To accommodate this and still allow e.g. currency formatting, the Intl.MessageFormat proposal's :number handler accepts as input numbers, BigInt, JSON string representations of numbers, or objects with a valueOf() method that returns a number or a BigInt. When using that last form, the object may also have an options property, and its values are merged into the MF2 expression options, and eventually passed to the Intl.NumberFormat constructor.
This allows for usage like:
const msg = new Intl.MessageFormat('en', 'Your total is {$price :number style=currency}')
const price = { valueOf: () => 42, options: { currency: 'EUR' } }
msg.format({ price }) // 'Your total is €42.00'
This kinda works, and seems like the least worst option at the moment. But it still feels somewhat hacky, esp. as it doesn't differentiate options like unit and currency as anything special.
It might be better to have some more explicit representation of number+currency and number+unit that could be supported also outside Intl.MessageFormat, in Intl.NumberFormat.
TG2 discussion notes: https://github.com/tc39/ecma402/blob/main/meetings/notes-2024-09-26.md#design-for-currency-and-unit-inputs-that-carry-their-values
Proposal: https://github.com/tc39/proposal-measure