Last active
March 28, 2024 16:19
-
-
Save joelstransky/f43bc4ba36b06698e1838dd83ec0ab91 to your computer and use it in GitHub Desktop.
Custom Intl.NumberFormat units
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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