File Size Formatter

So, you’ve got a filesize as bytes and you want to display it on your webpage. The trouble is that it could be 2 bytes or 2,000,000,000 Bytes (2GB). So how do you go about displaying that with a reasonable amount of accuracy without taking up the whole screen with zeros?

You use this function, of course:

function displaySize($x){
	// Takes an input in bytes and displays using the appropriate units. 

	// less than KB - show as bytes
	if ($x < 1000){
		return number_format($x, 0, '.', ',') . 'B';
	// between 1KB and 1MB - show as KB
	} else if($x >= 1000 && $x < 1000000) {
		$x = $x / 1000;
		return number_format($x, 2, '.', ',') . 'KB';
	// between 1MB and 1GB - show as MB
	} else if($x >= 1000000 && $x < 1000000000){
		$x = $x / 1000000;
		return number_format($x, 2, '.', ',') . 'MB';
	// greater than 1GB - show as GB
	} else {
		$x = $x / 1000000000;
		return number_format($x, 2, '.', ',') . 'GB';
	}
}

Obviously this only goes up to GB. I’ll leave it as an exercise for the reader to alter it to display TB or PB.

Advertisements

About Mr Chimp

I make music, draw pictures, browse the internet, programme, and make sweet, sweet cups of tea until the early hours.
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s