Last active
December 11, 2018 18:30
-
-
Save aalfiann/7862f0a2e1e74e7158691596c92bfb09 to your computer and use it in GitHub Desktop.
Convert bytes size to human readable (Pure JS)
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
/** | |
* 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