ecma402
ecma402 copied to clipboard
NumberFormat has odd behaviour for narrow/compact display of bytes
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.
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:
- The compact unit suffixes are not SI prefixes
- 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".
- The space is missing due to a CLDR bug which should be fixed in an upcoming release.
- 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
The proposal in question is https://github.com/tc39/ecma402/issues/277
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
CLDR issue: https://unicode-org.atlassian.net/browse/CLDR-17952