Skip to content

Instantly share code, notes, and snippets.

@xiaozhuai
Last active March 8, 2023 03:36
Show Gist options
  • Save xiaozhuai/17d5b70806d4bf9c52d9205a26095871 to your computer and use it in GitHub Desktop.
Save xiaozhuai/17d5b70806d4bf9c52d9205a26095871 to your computer and use it in GitHub Desktop.
Get a human readabe size
function toHumanReadableSize(bytes, precision = 1) {
if (typeof bytes !== 'number' || isNaN(bytes) || !isFinite(bytes)) return '-';
const units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB'];
let num = bytes;
let unit = 0;
if (bytes !== 0) {
unit = Math.floor(Math.log(bytes) / Math.log(1024));
num = bytes / Math.pow(1024, Math.floor(unit));
}
if (unit === 0) {
return num + ' ' + units[unit];
} else {
return num.toFixed(precision) + ' ' + units[unit];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment