ecma402 icon indicating copy to clipboard operation
ecma402 copied to clipboard

NumberFormat has odd behaviour for narrow/compact display of bytes

Open Naddiseo opened this issue 3 years ago • 4 comments
trafficstars

Hi there, not sure if this is the correct place to have this bug report, if not, please let me know.

What I'm trying to do: I'm looking to use the NumberFormatter to format file sizes in compact form and automatically adjust the units as the size grows. eg, KB, MB, GB, TB It seems to work except in the case of GB, and I could also just be plainly doing this incorrectly, but it is very strange behaviour. I can reproduce this on Edge, Chome, and Firefox.

How I'm doing it:

const fileSizeFormatter = new Intl.NumberFormat("en-CA", {
  notation: "compact",
  style: "unit",
  unit: "byte",
  unitDisplay: "narrow",
});

What I expect:

  fileSizeFormatter.format(123); /// 123B
  fileSizeFormatter.format(123_456); /// 123KB
  fileSizeFormatter.format(123_456_789); /// 123MB
  fileSizeFormatter.format(123_456_789_012); /// 123GB
  fileSizeFormatter.format(123_456_789_012_345); /// 123TB

What actually happens:

  fileSizeFormatter.format(123); /// 123B
  fileSizeFormatter.format(123_456); /// 123KB
  fileSizeFormatter.format(123_456_789); /// 123MB
  fileSizeFormatter.format(123_456_789_012); /// 123BB <-- this is using a "B" for "Billion" as a prefix
  fileSizeFormatter.format(123_456_789_012_345); /// 123TB

Again, I'm not sure if this is a bug, expected behaviour, or I'm just missing something obvious in the documentation.

Naddiseo avatar Nov 24 '22 22:11 Naddiseo

There are a couple intersecting issues here. The tl;dr is that you should use separate units "kilobyte", "megabyte", etc., until we have proper unit selection.

The full story is:

  1. The compact unit suffixes are not SI prefixes
  2. What you're really formating is "123 thousand bytes", which in short form should probably have a space: "123K B". You're not formating "123 kilobytes".
  3. The space is missing due to a CLDR bug which should be fixed in an upcoming release.
  4. There is an open proposal to perform actual unit selection so that you can get your desired behavior. It would look something like
{ unit: "byte", unitContext: "file-size" }

which would then choose the correct unit for file size given the input quantity.

CC @younies

sffc avatar Nov 25 '22 13:11 sffc

The proposal in question is https://github.com/tc39/ecma402/issues/277

KuSh avatar Dec 11 '23 10:12 KuSh

TG2 discussion: https://github.com/tc39/ecma402/blob/master/meetings/notes-2023-12-14.md#numberformat-has-odd-behaviour-for-narrowcompact-display-of-bytes-730

sffc avatar Dec 15 '23 00:12 sffc

CLDR issue: https://unicode-org.atlassian.net/browse/CLDR-17952

sffc avatar Oct 08 '24 02:10 sffc