Skip to content

Instantly share code, notes, and snippets.

@joelstransky
Last active March 28, 2024 16:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joelstransky/f43bc4ba36b06698e1838dd83ec0ab91 to your computer and use it in GitHub Desktop.
Save joelstransky/f43bc4ba36b06698e1838dd83ec0ab91 to your computer and use it in GitHub Desktop.
Custom Intl.NumberFormat units
sizeFormatter = new Intl.NumberFormat([], {
style: "unit",
unit: "byte",
notation: "compact",
unitDisplay: "narrow",
});
(_bytes) => {
const units = { B: " bytes", KB: " kb", MB: " mb", GB: " gb", TB: " tb" };
const parts = sizeFormatter.formatToParts(_bytes);
const vo: any = parts.reduce(
(a, part: Intl.NumberFormatPart) => {
a[part.type] = part.value;
return a;
},
{ decimal: "", fraction: "", compact: "" },
);
return `${vo.integer}${vo.decimal}${vo.fraction} ${units[`${vo.compact}${vo.unit}`]}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment