round

Rounds a float

Syntax

round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] ) : float

Parameters

val

The value to round.

precision

The optional number of decimal digits to round to. If the precision is positive, the rounding will occur after the decimal point. If the precision is negative, the rounding will occur before the decimal point. If the absolute value of the precision is greater than or equal to the number of digits, the result of the rounding is equal to 0

mode

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

Constants Description
PHP_ROUND_HALF_UP Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVEN Round val to precision decimal places towards the nearest even value.
PHP_ROUND_HALF_ODD Round val to precision decimal places towards the nearest odd value.

Return

The value rounded to the given precision as a float.

Examples

1 · val · Down

<?

$val = 1.4999;

$return = round($val);

echo $return;

?>
1

2 · val · Up

<?

$val = 1.5000;

$return = round($val);

echo $return;

?>
2

3 · precision

<?

$val = 5555.5555;

for($i = -5; $i < 5; ++$i)
{
    $precision = $i;
    
    $return = round($val, $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

4 · mode · PHP_ROUND_HALF_UP

<?

$vals = array(-2.5, -1.5, -0.5, 0.5, 1.5, 2.5);
$precision = 0;
$mode = PHP_ROUND_HALF_UP;

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

?>
-3
-2
-1
1
2
3

5 · mode · PHP_ROUND_HALF_DOWN

<?

$vals = array(-2.5, -1.5, -0.5, 0.5, 1.5, 2.5);
$precision = 0;
$mode = PHP_ROUND_HALF_DOWN;

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

?>
-2
-1
0
0
1
2

6 · mode · PHP_ROUND_HALF_EVEN

<?

$vals = array(-2.5, -1.5, -0.5, 0.5, 1.5, 2.5);
$precision = 0;
$mode = PHP_ROUND_HALF_EVEN;

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

?>
-2
-2
0
0
2
2

7 · mode · PHP_ROUND_HALF_ODD

<?

$vals = array(-2.5, -1.5, -0.5, 0.5, 1.5, 2.5);
$precision = 0;
$mode = PHP_ROUND_HALF_ODD;

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

?>
-3
-1
-1
1
1
3

abs

acos

acosh

asin

asinh

atan

atan2

atanh

base_convert

bindec

ceil

cos

cosh

decbin

dechex

decoct

deg2rad

exp

expm1

fdiv

floor

fmod

hexdec

hypot

intdiv

is_finite

is_infinite

is_nan

log

log10

log1p

max

min

octdec

pi

pow

rad2deg

sin

sinh

sqrt

tan

tanh

PHP

Home Menu