PHP – Bytes Converter ?>

PHP – Bytes Converter

A small function to convert bytes to B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB.

class BytesToString {
	public static function toString($value) {
		$suffix = array('B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB');
		
		$level = 0;
		
		while($value > 1024)
		{
			$value /= 1024;
			$level++;
		}
		
		return round($value,1) . ' ' . $suffix[$level];
	}
}

echo '<p>4200 bytes = ' . BytesToString::toString(4200) . '</p>';
echo '<p>4200000 bytes = ' . BytesToString::toString(4200000) . '</p>';
echo '<p>420000000 bytes = ' . BytesToString::toString(420000000) . '</p>';
echo '<p>42000000000 bytes = ' . BytesToString::toString(42000000000) . '</p>';
echo '<p>4200000000000 bytes = ' . BytesToString::toString(4200000000000) . '</p>';

// 4200 bytes = 4.1 KiB
// 4200000 bytes = 4 MiB
// 420000000 bytes = 400.5 MiB
// 42000000000 bytes = 39.1 GiB
// 4200000000000 bytes = 3.8 TiB

Leave a Reply

Your email address will not be published. Required fields are marked *

two × 1 =