0

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Be careful with round, I had it in my answer but chose to delete, it can be very useful but be weary as if you are trying to show how much disk space is needed for a file of 7.3MB and the user has 7.0MB free and your program outputs 7MB needed because it rounded down the user would not have enough room. However if you are safe and always round up (by useing ceil) the user will always be informed of the upper limit.
Is round capable of doing floor as well as ceil? I didn't think it was, I know you can control how it rounds halves, you cannot however override the default rounding of for example 7.3 or 7.7 they will always round down or up respectivley.
@JonTaylor You're right it does half up and half down. My comment is a bit misleading.
0

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

7 Comments

he was using ceil to do the rounding, since it looks like he always wants the next integer up, a good assumption if for example he is trying to show how much disk space is needed.
@Jon: in another comment above he wrote he prefers to use round.
I don;t see any such comment, I do however see a tag to round, it doesnt necesserily mean he wants the round function though.
I'm referring to the comment you replied to.
Well I wouldn't always say flat out that you must use something when it is often clear on SO that people don't always think of the consequences. For file sizes I would always use ceil if you are outputting to a user. I would never round down. Similarly for disk space I would always floor, never round up.
|
0
ceil($bytes / pow(1024, $unit));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.