How to format bytes to human readable Size in Python

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

Sample Python

fileSize = 12454162221
for count in ['Bytes','KB','MB','GB']:
    if fileSize > -1024.0 and fileSize < 1024.0:
        print "%3.1f%s" % (fileSize, count)
    fileSize /= 1024.0
print "%3.1f%s" % (fileSize, 'TB')

How to format bytes to human readable Size in Javascript

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];
}