All the answers to the question uses that 1 kilobyte = 1024 bytes which is wrong! (1 kibibyte = 1024 bytes)
since the question asks to convert file sizes, it should use that 1 kilobyte = 1000 bytes (see https://wiki.ubuntu.com/UnitsPolicy)
function format_bytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1000));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1000, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}