Search code examples
phpfloorceil

PHP ceil() and floor() returning float?


The PHP docs state the following for the ceil() function:

Return Values

value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

floor() also returns a float as return value. However, it makes no sense to me as to why. Why does a non-decimal return value need a range bigger than that of an integer?


Solution

  • It says so in the quote you cite: as the value range of float is usually bigger than that of integer. If you return an int (or a long), chances are that your original value falls outside the range of numbers that can possibly be represented by said int or long.

    Follow-up question & answer:

    What do you mean by "your original value falls outside the range of numbers"? I mean, the purpose of ceil() and floor() is to round up and down numbers to a whole number (integer) after all?

    (Audite Marlow Apr 6 '16 at 15:19)

    Yes, but if you have an unsigned number that is higher than four billion and something or a signed number that is bigger than half of that, it can not be contained in an int, because the number is too big to fit inside a four-byte integer.

    The same goes for numbers that are too big to fit inside an eight-byte integer (a long).

    If I'm not mistaken, a double (which is an eight-byte floating point number) has the range of 10^-308 to 10^+308, which is MUCH broader than the range of possible values of a long.

    If you want to ceil or floor a number with a rough value of 10^100, you cannot fit that into an int or a long, so only a float (or double) will do.

    (this answer has been synthesised long after the question has been asked, to provide an actual answer to the question instead of leaving it open with only a few comments)