Mastering PHP’s round() Function: Precise Rounding Techniques
This guide explains PHP's round() function, detailing its syntax, parameters, rounding modes, and return values, and provides practical code examples that demonstrate how to achieve accurate numeric rounding for various precision and mode settings.
The round() function in PHP returns the value of a number rounded to a specified precision, optionally using a chosen rounding mode.
Syntax:
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )Parameters $val – the number to be rounded. $precision – optional; the number of decimal digits to round to. It can be zero, positive, or negative. $mode – optional; one of the constants PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD, defining how .5 values are handled.
Return value
The function returns the rounded number as a float.
Examples
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>These examples illustrate default rounding (half up) and how specifying precision or a negative precision affects the result.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.
