How to Use PHP's round() Function for Precise Number Rounding
This article explains PHP's round() function, covering its basic usage, optional precision and rounding mode parameters, and provides multiple code examples demonstrating rounding of positive, negative, and specially‑mode‑controlled numbers.
The round() function in PHP is used to round a floating‑point number to a specified precision. Its basic usage requires only the number to be rounded as an argument.
round() accepts up to three parameters: the number to round, an optional number of decimal places, and an optional rounding mode. If the second parameter is omitted, the function rounds to the nearest integer; otherwise it rounds to the given number of decimal places.
Usage Examples
Example 1
<code>$num = 3.14;
echo round($num); // outputs 3</code>In this example, 3.14 is passed to round() , which rounds it to the nearest integer, producing 3.
Example 2
<code>$num1 = 3.14159;
$num2 = 3.14159;
$num3 = 3.14159;
echo round($num1, 2); // outputs 3.14
echo round($num2, 3); // outputs 3.142
echo round($num3, 4); // outputs 3.1416</code>Here the second argument specifies the number of decimal places, so the function returns 3.14, 3.142, and 3.1416 respectively.
The round() function also handles negative numbers. When a negative value is provided, the fractional part is rounded in the usual way.
<code>$num = -3.14159;
echo round($num); // outputs -3</code>Passing -3.14159 results in -3 after rounding.
Additionally, round() can accept a third optional parameter to define the rounding mode. By default PHP uses PHP_ROUND_HALF_UP (standard rounding). Other modes include PHP_ROUND_HALF_DOWN , PHP_ROUND_HALF_EVEN , etc.
Example 3
<code>$num = 3.5;
echo round($num, 0, PHP_ROUND_HALF_UP); // outputs 4
echo round($num, 0, PHP_ROUND_HALF_DOWN); // outputs 3</code>With the same number 3.5, using PHP_ROUND_HALF_UP rounds up to 4, while PHP_ROUND_HALF_DOWN rounds down to 3.
Notes
The round() function only affects the fractional part of a number; if an integer is passed, it is returned unchanged.
Summary
The round() function in PHP provides a simple way to round floating‑point numbers. You can control the number of decimal places with the second argument and the rounding behavior with the optional third argument, while remembering that the function does not modify integer values.
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.