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

How to convert bytes to human readable file size in PHP

To convert bytes to human readable file size in PHP you can use the following snippet.

Sample PHP

function BytesToHumanReadableSize($bytes)
{
	$unit = null;
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
	
	for($Counter = 0, $c = count($units); $Counter < $c; $Counter++)
	{
		if ($bytes > 1024)
		{
			$bytes = $bytes / 1024;
		}
		else
		{
			$unit = $units[$Counter];
			break;
		}
	}
 
	return round($bytes, 2). ' ' .$unit;
}