Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

round

Description

The round of Math for PHP rounds a float.

Syntax

round(
    int|float $num,
    int $precision = 0,
    int $mode = PHP_ROUND_HALF_UP
): float

Parameters

num

The value to round.

precision

The optional number of decimal digits to round to.

If the precision is positive, num is rounded to precision significant digits after the decimal point.

If the precision is negative, num is rounded to precision significant digits before the decimal point, i.e. to the nearest multiple of pow(10, -$precision), e.g. for a precision of -1 num is rounded to tens, for a precision of -2 to hundreds, etc.

mode

Use one of the following constants to specify the mode in which rounding occurs.

ConstantsDescription
PHP_ROUND_HALF_UPRounds num away from zero when it is half way there, making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWNRounds num towards zero when it is half way there, making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVENRounds num towards the nearest even value when it is half way there, making both 1.5 and 2.5 into 2.
PHP_ROUND_HALF_ODDRounds num towards the nearest odd value when it is half way there, making 1.5 into 1 and 2.5 into 3.

Return

The value rounded to the given precision as a float.

Examples

1 · num · down

<?

$num = 1.4999;

$return = round($num);

echo $return;

?>
1

2 · num · up

<?

$num = 1.5000;

$return = round($num);

echo $return;

?>
2

3 · precision

<?

$num = 5555.5555;

for($i = -5; $i <= 5; ++$i)
{
    $precision = $i;
    
    $return = round($num, $precision);
    
    echo $precision . ": " . $return . PHP_EOL;
}

?>
-5: 0
-4: 10000
-3: 6000
-2: 5600
-1: 5560
0: 5556
1: 5555.6
2: 5555.56
3: 5555.556
4: 5555.5555
5: 5555.5555

4 · mode · PHP_ROUND_HALF_UP

<?

$nums = [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5];
$precision = 0;
$mode = PHP_ROUND_HALF_UP;

for($i = 0; $i < count($nums); ++$i)
{
    $return = round($nums[$i], $precision, $mode);
    
    echo $return . PHP_EOL;
}

?>
-3
-2
-1
1
2
3

5 · mode · PHP_ROUND_HALF_DOWN

<?

$nums = [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5];
$precision = 0;
$mode = PHP_ROUND_HALF_DOWN;

for($i = 0; $i < count($nums); ++$i)
{
    $return = round($nums[$i], $precision, $mode);
    
    echo $return . PHP_EOL;
}

?>
-2
-1
0
0
1
2

6 · mode · PHP_ROUND_HALF_EVEN

<?

$nums = [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5];
$precision = 0;
$mode = PHP_ROUND_HALF_EVEN;

for($i = 0; $i < count($nums); ++$i)
{
    $return = round($nums[$i], $precision, $mode);
    
    echo $return . PHP_EOL;
}

?>
-2
-2
0
0
2
2

7 · mode · PHP_ROUND_HALF_ODD

<?

$nums = [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5];
$precision = 0;
$mode = PHP_ROUND_HALF_ODD;

for($i = 0; $i < count($nums); ++$i)
{
    $return = round($nums[$i], $precision, $mode);
    
    echo $return . PHP_EOL;
}

?>
-3
-1
-1
1
1
3
HomeMenu