Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an option in Intl.NumberFormat() to automatically convert to bigger units?

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?

like image 993
Sebastian Zartner Avatar asked Feb 01 '26 12:02

Sebastian Zartner


1 Answers

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:

  1. Use the compact notation.
  2. Use unit as your style, and provide byte as the unit.
  3. Set 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));
like image 117
andrec93 Avatar answered Feb 04 '26 02:02

andrec93



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!