Convert number of bytes into human readable format in JavaScript.
/**
* 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 byteFormat(bytes, precision) {
var isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
if (!isNumber(bytes)) {
return "0 B";
}
var kilobyte = 1024,
megabyte = kilobyte * 1024,
gigabyte = megabyte * 1024,
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';
}
}
// or
function byteFormat (bytes, precision) {
var suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
factor = Math.pow(10, precision > 0 ? precision : 2);
for (var i = bytes, k = 0; i >= 1024 && k < suffixes.length; i /= 1024, k++) {}
return (Math.round(i * factor) / factor) + ' ' + suffixes[k];
}
console.log(byteFormat(1024 * 1024 * 1024));