To format bytes to human readable Size in Javascript you can use the following snippet.

Sample Javascript

function BytesToHumanReadableSize(bytes){
	if(!bytes) {return '0 bytes';}
    var sizeUnits = ['bytes','KB','MB','GB','TB','PB','EB','ZB','YB'];
    var calc = Math.floor( Math.log(bytes) / Math.log(1024) );
    calc = Math.min( Math.max(0,calc), sizeUnits.length-1);
    var bytesNew = Math.round((bytes/ Math.pow(1024,calc))*100)/100;
    return bytesNew + ' ' + sizeUnits[calc];
}

2 thought on “How to format bytes to human readable Size in Javascript”

Leave a Reply