Skip to content

Instantly share code, notes, and snippets.

@fvdm
Created January 29, 2015 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fvdm/68f5793d95cf65ae1be2 to your computer and use it in GitHub Desktop.
Save fvdm/68f5793d95cf65ae1be2 to your computer and use it in GitHub Desktop.
Number.humanBytes()
// Convert bytes to string '123.6 KiB', MiB, etc.
// var bytes = 8765432
// var human = bytes.humanBytes( 2 )
// 8.36 MiB
Number.prototype.humanBytes = function( decimals ) {
var units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
var unit = 'B';
var bytes = this.valueOf();
var dec = decimals ? Math.pow( 10, decimals ) : 1;
var i = 0;
while( bytes >= 1024 ) {
if( units[i] == undefined ) {
break;
}
bytes = bytes / 1024;
unit = units[i];
i++;
}
bytes = Math.round( bytes * dec ) / dec;
return bytes +' '+ unit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment