In PHP development, we often need to round floating point numbers. Although the intval() function can convert variables into integers, it does not support upward rounding (i.e., "ceiling" operation), it simply truncates the fractional part and rounds the result downward. In order to achieve the effect of upward rounding, it is usually necessary to use it in conjunction with other functions, such as ceil() .
This article will introduce how to combine ceil() and intval() functions to realize the function of first rounding up and then converting into integers, and explain the details that need to be paid attention to when using it.
The intval() function is used to convert a variable to an integer type, and the syntax is as follows:
intval(mixed $var, int $base = 10): int
It will truncate the fractional part directly:
<?php
var_dump(intval(4.7)); // Output int(4)
var_dump(intval(-3.9)); // Output int(-3)
?>
As can be seen from the above example, intval() does not round or round the decimal part.
The ceil() function is used to round up the floating point number, returning the smallest integer greater than or equal to the given number, and the result type is a floating point number.
ceil(float $value): float
Example:
<?php
var_dump(ceil(4.1)); // Output float(5)
var_dump(ceil(-3.7)); // Output float(-3)
?>
Note that ceil() returns a floating point number. If an integer type is required, it still needs to be converted.
If you want to round a floating point number up first and then convert it to an integer type, you can first round it with ceil() and then convert it with intval() :
<?php
$num = 4.3;
$intNum = intval(ceil($num));
echo $intNum; // Output 5
?>
This achieves the purpose of "rounding up and converting into integers".
<?php
function ceilToInt($num) {
return intval(ceil($num));
}
// test
$values = [3.2, 5.9, -2.7, -4.0];
foreach ($values as $val) {
echo "Original value: $val, Integer after rounding up: " . ceilToInt($val) . "\n";
}
?>
Running results:
Original value: 3.2, Integer after rounding up: 4
Original value: 5.9, Integer after rounding up: 6
Original value: -2.7, Integer after rounding up: -2
Original value: -4, Integer after rounding up: -4
Scenario : It is very practical when you need to round up the price, page number, quantity, etc., and you need integer types.
Notice :
ceil() returns a floating point number, and must use intval() or cast to obtain the integer.
Intval() handles negative numbers by truncating the fractional part, not rounding it. It cannot be rounded upwards when used alone.
When combined, the order cannot be reversed. For example, ceil(intval($num)) is not equivalent to intval(ceil($num)) .
Suppose you want to process a URL parameter containing a number and round the parameter up to an integer: