Created
June 19, 2015 12:29
-
-
Save Hellowlol/9a8ca01b94180fdd2124 to your computer and use it in GitHub Desktop.
bytes to filesize javascript
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 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