Skip to content

Instantly share code, notes, and snippets.

@aalfiann
Last active December 11, 2018 18:30
Show Gist options
  • Save aalfiann/7862f0a2e1e74e7158691596c92bfb09 to your computer and use it in GitHub Desktop.
Save aalfiann/7862f0a2e1e74e7158691596c92bfb09 to your computer and use it in GitHub Desktop.
Convert bytes size to human readable (Pure JS)
/**
* Convert bytes size to human readable
* @param bytes = input bytes value
* @param si = input boolean true is for byte and false is for bits
*
* @return formatted bytes
*/
function humanFileSize(bytes, si) {
si=(si===undefined)?true:si;
var thresh = si ? 1000 : 1024;
if(Math.abs(bytes) < thresh) {
return bytes + ' B';
}
var units = si
? ['KB','MB','GB','TB','PB','EB','ZB','YB']
: ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while(Math.abs(bytes) >= thresh && u < units.length - 1);
return bytes.toFixed(1)+' '+units[u];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment