round() function in PHP

PHPProgrammingServer Side Programming

The round() function rounds a floating point number. For example, 0.90 to 1, 0.35 to 0, etc.

Syntax

round(val, precision, mode)

Parameters

  • val − The value to round

  • precision − It sets the precision i.e. the number of decimal digits to round to

  • mode − A constant that specify the following rounding mode

    • PHP_ROUND_HALF_UP - The constant rounds val up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2. Default

    • PHP_ROUND_HALF_DOWN - The constant rounds val down to precision decimal places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1

    • PHP_ROUND_HALF_EVEN - It rounds val to precision decimal places towards the next even value

    • PHP_ROUND_HALF_ODD - It rounds val to precision decimal places towards the next odd value.

Return

The round() function Returns the rounded value.

Example

 Live Demo

<?php
   echo(round(2.099,2));
?>

Output

2.1

Example

Let us see another example −

 Live Demo

<?php
   echo(round(9.859,2));
?>

Output

9.86

Example

Let us see another example −

 Live Demo

<?php
   echo(round(10.5,0,PHP_ROUND_HALF_UP) . "<br>");
   echo(round(-10.5,0,PHP_ROUND_HALF_UP) );
?>

Output

11<br>-11

Example

Let us see another example −

 Live Demo

<?php
   echo(round(19.5,0,PHP_ROUND_HALF_DOWN) . "<br>");
   echo(round(-19.5,0,PHP_ROUND_HALF_DOWN) . "<br>");
?>

Output

19<br>-19<br>

Example

Let us see another example −

 Live Demo

<?php
   echo(round(9.9,0,PHP_ROUND_HALF_EVEN) . "<br>");
   echo(round(-9.8,0,PHP_ROUND_HALF_EVEN) . "<br>");
   echo(round(11.8,0,PHP_ROUND_HALF_ODD) . "<br>");
   echo(round(-11.8,0,PHP_ROUND_HALF_ODD));
?>

Output

10<br>-10<br>12<br>-12
raja
Published on 09-Nov-2018 12:21:06
Advertisements