user495915
user495915

Reputation: 185

PHP – Round number

This piece of code reads the size of a file, but the output for a file that is 1.759864Mb will be 1Mb and I'd like it to be 2Mb. I know that it's about changing one little thing but I can't find what it is...

function Size($path)
{
    $bytes = sprintf('%u', filesize($path));
    if ($bytes > 0)
    {
        $unit = intval(log($bytes, 1024));
        $units = array('B', 'Kb', 'Mb', 'Gb');

        if (array_key_exists($unit, $units) === true)
        {
            return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
        }
    }
    return $bytes;
}

Upvotes: 0

Views: 346

Answers (3)

Luc CR
Luc CR

Reputation: 1126

ceil($bytes / pow(1024, $unit));

Upvotes: 0

Jocelyn
Jocelyn

Reputation: 11393

I suggest using PHP round function instead of just letting sprintf do the rounding (with %d):

return sprintf('%d %s', round($bytes / pow(1024, $unit)), $units[$unit]);

Upvotes: 0

user1440875
user1440875

Reputation:

It should be

return sprintf('%d %s', ceil($bytes / pow(1024, $unit)), $units[$unit]);

ceil returns the next highest integer value by rounding up value if necessary.

Upvotes: 3

Related Questions