Current Location: Home> Latest Articles> Is it normal that ceil() returns a float instead of an int?

Is it normal that ceil() returns a float instead of an int?

M66 2025-06-30

In PHP, the ceil() function is used to round a number up, returning the smallest integer value greater than or equal to the given number. Many developers notice that the result returned by ceil() is a float, not the expected int. Is this normal? Is there a type conversion issue? This article will analyze the return type of the ceil() function and explain why this happens.

1. Definition and Return Type of the ceil() Function

According to the official PHP documentation, the definition of the ceil() function is as follows:

float ceil(float $value)

This means that ceil() accepts a float parameter and returns a float. Example code:

<?php
$num = 3.14;
$result = ceil($num);
var_dump($result); // Output: float(4)
?>

Output:

float(4)

Although the result is the integer 4, the data type is still a float.

2. Why does ceil() return a float instead of an int?

This is because PHP's design dictates that the return value of ceil() will always be a float. Even though the logic of ceil() is to round a number to an integer, its return type remains a float. This ensures consistency in subsequent mathematical operations or when mixed with floating-point calculations.

For example:

<?php
$num = 7.1;
echo ceil($num) + 1.5;  // Result: 9.5
?>

If ceil() returned an int, PHP might need to convert the int to a float before performing floating-point addition. By keeping the return as a float, unnecessary type conversion is avoided.

3. How to Convert the Result of ceil() to an Integer?

If you explicitly need an integer type, you can use type casting or the intval() function:

<?php
$num = 4.7;
$ceil_float = ceil($num);       // float(5)
$ceil_int = (int) $ceil_float;  // int(5)
var_dump($ceil_int);
?>

This way, you can obtain the result as an integer type.

4. Real-World Example

<?php
// Test ceil() return type
$value = 5.3;
$result = ceil($value);
echo "ceil({$value}) = {$result}\n";    // Result: 6
echo "Type: " . gettype($result) . "\n"; // Type: float
<p>// Type cast to int<br>
$int_result = (int) $result;<br>
echo "Type after casting to int: " . gettype($int_result) . "\n";  // int<br>
?><br>

Output:

ceil(5.3) = 6
Type: double
Type after casting to int: integer

5. Conclusion

  • The return type of the ceil() function is float, which is the normal behavior according to PHP's design.

  • Even if the returned value is an integer, its data type remains float.

  • If an integer type is required, you can use type casting (int) or the intval() function.

  • Maintaining the float type helps avoid multiple type conversions between float and int, thus improving calculation performance.