Skip to content

Instantly share code, notes, and snippets.

@Hellowlol
Created June 19, 2015 12:29
Show Gist options
  • Save Hellowlol/9a8ca01b94180fdd2124 to your computer and use it in GitHub Desktop.
Save Hellowlol/9a8ca01b94180fdd2124 to your computer and use it in GitHub Desktop.
bytes to filesize javascript
function humanFileSize(bytes, pre, si) {
// Set default args
si = typeof si === 'undefined' ? true:false;
pre = typeof pre === 'undefined' ? 0:pre;
var thresh = si ? 1000 : 1024;
if(Math.abs(bytes) < thresh) {
return bytes.toFixed(pre) + ' 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(pre)+ ' ' +units[u];
}
console.log(humanFileSize(1, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment