Skip to content

Instantly share code, notes, and snippets.

@tobyjsullivan
Created November 20, 2020 20:38
Show Gist options
  • Save tobyjsullivan/ba6670b3a17b81b099e7005107bdfec8 to your computer and use it in GitHub Desktop.
Save tobyjsullivan/ba6670b3a17b81b099e7005107bdfec8 to your computer and use it in GitHub Desktop.
Format File Sizes in JavaScript
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