Skip to content

Instantly share code, notes, and snippets.

@fvdm
Last active October 7, 2015 08:07
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/3132128 to your computer and use it in GitHub Desktop.
Save fvdm/3132128 to your computer and use it in GitHub Desktop.
Convert bytes to KiB, MiB, etc.
// Convert bytes to KiB, MiB, etc. (object)
// humanBytes( number, numDecimals )
// ex. humanBytes( 10714 ) = { number: 10, str: "10 KiB", unit: "KiB" }
// ex. humanBytes( 10714 ).str = "10 KiB"
// ex. humanBytes( 10714, 2 ).str = "10.46 KiB"
function humanBytes( bytes, decimals ) {
var units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
var unit = 'B';
var num = bytes;
var dec = decimals !== undefined ? Math.pow( 10, decimals ) : 1;
var i = 0;
while( num >= 1024 ) {
if( units[i] == undefined ) {
break;
}
num = num / 1024;
unit = units[i];
i++;
}
num = Math.round( num * dec ) / dec;
return {
str: num +' '+ unit,
unit: unit,
number: num
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment