Last active
March 8, 2023 03:36
-
-
Save xiaozhuai/17d5b70806d4bf9c52d9205a26095871 to your computer and use it in GitHub Desktop.
Get a human readabe size
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
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