Convert size in bytes to human readable format (JavaScript)
This is JavaScript implementation of the function described in my earlier article Convert size in bytes to a human readable format (PHP). Please see the link for more in-depth explanation of the function workflow.
- /**
- * Convert number of bytes into human readable format
- *
- * @param integer bytes Number of bytes to convert
- * @param integer precision Number of digits after the decimal separator
- * @return string
- */
- function bytesToSize(bytes, precision)
- {
- var kilobyte = 1024;
- var megabyte = kilobyte * 1024;
- var gigabyte = megabyte * 1024;
- var terabyte = gigabyte * 1024;
- if ((bytes >= 0) && (bytes < kilobyte)) {
- return bytes + ' B';
- } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
- return (bytes / kilobyte).toFixed(precision) + ' KB';
- } else if ((bytes >= megabyte) && (bytes < gigabyte)) {
- return (bytes / megabyte).toFixed(precision) + ' MB';
- } else if ((bytes >= gigabyte) && (bytes < terabyte)) {
- return (bytes / gigabyte).toFixed(precision) + ' GB';
- } else if (bytes >= terabyte) {
- return (bytes / terabyte).toFixed(precision) + ' TB';
- } else {
- return bytes + ' B';
- }
- }



If you want a decimal instead of rounding. Replace Math.Round with .toFixed(); function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return 'n/a'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]; };We could extend the units to cover more units. var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; We could also use SI binary prefixes instead of SI decimal prefixed. var sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];The above function I wrote will print '8.0 bytes', you probably want that to be just '8 bytes'. function bytesToSize(bytes) { var sizes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; if (bytes == 0) return 'n/a'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); if (i == 0) { return (bytes / Math.pow(1024, i)) + ' ' + sizes[i]; } return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]; }No offense guys but the floor/round/pow,... shizzle seems a lil over the top for such a function. It results in an "incorrect" space shown by all the rounds. Furthermore parseInt... Really? :p There is no need for that. Just wrote this function in a minute and I would think it would give more decent result and the calculation time should be alot shorter. function bytesToSize(bytes, precision) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; var posttxt = 0; if (bytes == 0) return 'n/a'; while( bytes >= 1024 ) { posttxt++; bytes = bytes / 1024; } return bytes.toFixed(precision) + " " + sizes[posttxt]; } Hopes this helps someone else!