Using the ceil() Function in PHP to Round Numbers Upward
This article explains PHP's ceil() function, detailing its syntax, parameters, and behavior for rounding numbers upward, and provides three clear code examples demonstrating its use with positive, negative, and integer values, along with the expected output for each case.
In PHP, the ceil() function is used to round a floating‑point number up to the smallest integer that is greater than or equal to the original value.
Syntax of the ceil() function
<code>float ceil(float $number)</code>The parameter $number represents the value to be rounded up. The function returns the smallest integer that is greater than or equal to $number .
Using the ceil() function
Example 1:
<code>$number = 3.14;
$ceilNumber = ceil($number);
echo "Rounded up result: " . $ceilNumber;</code>The code above outputs:
<code>Rounded up result: 4</code>Here, a floating‑point number $number of 3.14 is rounded up, resulting in 4, which is the smallest integer not less than 3.14.
Example 2:
<code>$number = -5.7;
$ceilNumber = ceil($number);
echo "Rounded up result: " . $ceilNumber;</code>The code above outputs:
<code>Rounded up result: -5</code>In this case, the negative floating‑point number $number of -5.7 is rounded up to -5, the smallest integer that is greater than or equal to -5.7.
Example 3:
<code>$number = 10;
$ceilNumber = ceil($number);
echo "Rounded up result: " . $ceilNumber;</code>The code above outputs:
<code>Rounded up result: 10</code>When $number is already an integer (10), ceil() returns the original value unchanged because it is already the smallest integer not less than itself.
In summary, the ceil() function in PHP is a practical tool for rounding up both floating‑point numbers and integers, and the provided examples clearly demonstrate its usage and effects in various scenarios.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.