I'd like Intl.NumberFormat()
to automatically convert between units from smaller to bigger ones based on common rules. I.e. a given number should be converted to between centimeters, meters, and kilometers in the output depending on how big the number is.
Code examples:
const bytes = 1000000;
const transferSpeed = new Intl.NumberFormat('en-US',
{style: 'unit', unit: 'byte-per-second', unitDisplay: 'narrow'}).format(bytes);
console.log(transferSpeed);
const days = 365;
const timespan = new Intl.NumberFormat('en-US',
{style: 'unit', unit: 'day', unitDisplay: 'long'}).format(days);
console.log(timespan);
The output of these two calls is:
1,000,000B/s
365 days
In that case I'd expect this, though:
1MB/s
1 year
And one might want to define the threshold for when to convert to the next bigger unit. So it could be that the conversion should happen once the exact value is reached but also earlier, let's say at 90% of the next bigger unit. Given the examples above, the output would then be this:
0.9MB/s
0.9 years
Are there configuration options for the API to do that?
Not exactly a full answer to the question, but I thought I dropped this here in case it can help anybody.
Something close to this is actually possible with Intl.NumberFormat, but it has some limitations. If you wanted to format byte values, for instance, you could:
compact
notation.unit
as your style, and provide byte
as the unit.narrow
as unitDisplay
.With these options, the formatter will correctly convert from one unit to the other and, thanks to the unitDisplay
value, it will display the unit of measurement as you would expect.
This is of course only usable with the few supported units for which this makes sense, and it limits you to have the unit right next to value, even though that's usually what you'd want anyway. Browser support may also be an issue if you need to target older platforms.
Here's a sample.
const byteValueNumberFormatter = Intl.NumberFormat("en", {
notation: "compact",
style: "unit",
unit: "byte",
unitDisplay: "narrow",
});
console.log(byteValueNumberFormatter.format(10));
console.log(byteValueNumberFormatter.format(200000));
console.log(byteValueNumberFormatter.format(50000000));