Categories
PHP

Ceil, Floor, and Round

Rounding float values up or down with ceil, floor, and round functions.

<?php
 echo floor (10.4); # 10
 echo ceil  (10.4); # 11
 echo round (10.4); # 10
 echo round (10.5); # 11

ceil() – round value to next highest integer

<?php
 //Syntax
 ceil(int|float $num): float

The ceil() function returns the value rounded up to the next highest integer. The return value is still of type float as the value range of float is usually bigger than that of integer.

Example:

<?php
 echo ceil(3.001); # Prints: 4
 echo ceil(7.99);  # Prints: 8
 echo ceil(-4.14341); #Prints: -3

floor() – round value to next lowest integer

<?php
 //Syntax
 floor(int|float $num): float

The floor() function returns the value rounded up to the next lowest integer. The return value is still of type float as the value range of float is usually bigger than that of integer.

Example:

 <?php
 echo floor(3.001); # Prints: 3
 echo floor(7.99);  # Prints: 7
 echo floor(-4.14341); #Prints: -5

round()

<?php
 //Syntax
 round(int|float $num, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float

The round function takes three parameters:

  1. $num: The input floating point number.
  2. $precision (optional): The number of decimal digits to round to, the default value is 0.
  3. $mode (optional):
    • PHP_ROUND_HALF_UP (default)
      Rounds value away from zero when it is half way there, making 10.5 into 11 and -10.5 into -11.
    • PHP_ROUND_HALF_DOWN
      Rounds value towards zero when it is half-way there, making 10.5 into 10 and -10.5 into -10.
    • PHP_ROUND_HALF_EVEN
      Rounds value towards the nearest even value, for example, making 9.5 and 10.5 into 10 and 12 respectively.
    • PHP_ROUND_HALF_ODD
      Rounds value towards the nearest odd value, for example, making 9.5 and 10.5 into 11.

Rounding by default is to zero decimal places, but the precision can be specified with the optional precision argument. By default, 10.4 rounds down to 10, and 10.5 rounds up to 11. The following examples show rounding at various precisions:

<?php	
 echo round(10.4999) . '<br>'; # 10
 echo round(10.5455) . '<br>'; # 11
 
 echo round(10.4999, 2) . '<br>'; # 10.5
 echo round(10.5455, 2) . '<br>'; # 10.55

 echo round(10.4999, 3) . '<br>'; # 10.5
 echo round(10.5455, 3) . '<br>'; # 10.546

Example: Using $mode constants

<?php
 echo round (10.5,0, PHP_ROUND_HALF_ODD). '<br>' ; #11;
 echo round (11.5,0, PHP_ROUND_HALF_ODD). '<br>' ; #11;

 echo round (10.5,0, PHP_ROUND_HALF_EVEN). '<br>'; #10;
 echo round (11.5,0, PHP_ROUND_HALF_EVEN). '<br>'; #12;

Doing Math:

  1. Finding absolute value, lowest value, and highest value
  2. Using Ceil, Floor, and Round functions
  3. Generating random numbers
  4. Converting numbers between decimal, binary, octal, and hexadecimal