Created
November 20, 2020 20:38
-
-
Save tobyjsullivan/ba6670b3a17b81b099e7005107bdfec8 to your computer and use it in GitHub Desktop.
Format File Sizes in JavaScript
This file contains hidden or 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
const UNITS = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte']; | |
function beautifulFilesize(filesizeBytes) { | |
let unitIdx = 0; | |
let magnitude = filesizeBytes; | |
while (magnitude > 1000 && unitIdx < UNITS.length - 1) { | |
unitIdx++; | |
magnitude /= 1000.0; | |
} | |
const numberFmt = new Intl.NumberFormat('en', { | |
maximumFractionDigits: unitIdx == 0 ? 0 : 2, | |
minimumFractionDigits: unitIdx == 0 ? 0 : 2, | |
style: 'unit', | |
unit: UNITS[unitIdx], | |
unitDisplay: 'short', // Options are "long" ("1.23 megabytes"), "short" ("1.23 MB"), and "narrow" ("1.23MB") | |
}); | |
return numberFmt.format(magnitude); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment