Numerical Functions in PHP

abs() — Absolute value

ceil() — Round fractions up

floor() — Round fractions down

fmod() — Returns the floating point remainder (modulo) of the division of the arguments

is_finite() — Finds whether a value is a legal finite number

is_infinite() — Finds whether a value is infinite

is_nan() — Finds whether a value is not a number

max() — Find highest value

min() — Find lowest value

round() — Rounds a float

PHP abs() Function

What does abs() do?

The PHP abs() function will give you the absolute value of number.

PHP abs() Syntax

abs ( mixed \$number ) : number

PHP abs() Parameters

1. number — The numeric value to process

PHP abs() Return Value

The PHP abs() function returns type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

PHP abs() Working Examples

1. abs() example

<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5);    // 5 (integer)
echo abs(-5);   // 5 (integer)
?>

Additional Tips from Fellow Developers

Contributed By: eep2004

<?php
\$arr = array();
for (\$i = 0; \$i < 1000; \$i++) \$arr[] = rand(-100, 100);
\$start = microtime(true);
for (\$i = 0; \$i < 1000; \$i++){
foreach (\$arr as \$v) \$v = abs(\$v);
}
echo number_format(microtime(true) - \$start, 4).'<br />';
\$start = microtime(true);
for (\$i = 0; \$i < 1000; \$i++){
foreach (\$arr as \$v) if (\$v < 0) \$v = abs(\$v);
}
echo number_format(microtime(true) - \$start, 4).'<br />';
\$start = microtime(true);
for (\$i = 0; \$i < 1000; \$i++){
foreach (\$arr as \$v) if (\$v < 0) \$v *= -1;
}
echo number_format(microtime(true) - \$start, 4).'<br />';
?>
Result:
1.4061
0.9697
0.2805
Conclusion: better to check before using the feature that the number is less than zero. Even better use multiplication by -1 than this function.

PHP ceil() Function

What does ceil() do?

The PHP ceil() function will give you the next highest integer value by rounding up value if necessary.

PHP ceil() Syntax

ceil ( float \$value ) : float

PHP ceil() Parameters

1. value — The value to round

PHP ceil() Return Value

The PHP ceil() function returns value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

PHP ceil() Working Examples

1. ceil() example

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

Additional Tips from Fellow Developers

Contributed By: Scott Weaver / scottmweaver * gmail

I needed this and couldn't find it so I thought someone else wouldn't have to look through a bunch of Google results-
<?php
// duplicates m\$ excel's ceiling function
if( !function_exists('ceiling') )
{
function ceiling(\$number, \$significance = 1)
{
return ( is_numeric(\$number) && is_numeric(\$significance) ) ? (ceil(\$number/\$significance)*\$significance) : false;
}
}
echo ceiling(0, 1000);     // 0
echo ceiling(1, 1);        // 1000
echo ceiling(1001, 1000);  // 2000
echo ceiling(1.27, 0.05);  // 1.30
?>

Contributed By: eep2004

Caution!
<?php
\$value = 77.4;
echo ceil(\$value * 100) / 100;         // 77.41 - WRONG!
echo ceil(round(\$value * 100)) / 100;  // 77.4 - OK!

Contributed By: steve_phpnet // nanovox \\ com

I couldn't find any functions to do what ceiling does while still leaving I specified number of decimal places, so I wrote a couple functions myself.  round_up is like ceil but allows you to specify a number of decimal places.  round_out does the same, but rounds away from zero.
<?php
// round_up:
// rounds up a float to a specified number of decimal places
// (basically acts like ceil() but allows for decimal places)
function round_up (\$value, \$places=0) {
if (\$places < 0) { \$places = 0; }
\$mult = pow(10, \$places);
return ceil(\$value * \$mult) / \$mult;
}
// round_out:
// rounds a float away from zero to a specified number of decimal places
function round_out (\$value, \$places=0) {
if (\$places < 0) { \$places = 0; }
\$mult = pow(10, \$places);
return (\$value >= 0 ? ceil(\$value * \$mult):floor(\$value * \$mult)) / \$mult;
}
echo round_up (56.77001, 2); // displays 56.78
echo round_up (-0.453001, 4); // displays -0.453
echo round_out (56.77001, 2); // displays 56.78
echo round_out (-0.453001, 4); // displays -0.4531
?>

PHP floor() Function

What does floor() do?

The PHP floor() function will give you the next lowest integer value (as float) by rounding down value if necessary.

PHP floor() Syntax

floor ( float \$value ) : float

PHP floor() Parameters

1. value — The numeric value to round

PHP floor() Return Value

The PHP floor() function returns value of floor() is still of type float because the value range of float is usually bigger than that of integer. This function return FALSE in case of an error (e.g. passing an array).

PHP floor() Working Examples

1. floor() example

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

Additional Tips from Fellow Developers

Contributed By: seppili_

I use this function to floor with decimals:
<?php
function floordec(\$zahl,\$decimals=2){
return floor(\$zahl*pow(10,\$decimals))/pow(10,\$decimals);
}
?>

Contributed By: greene dot mc

I believe this behavior of the floor function was intended.  Note that it says "the next lowest integer".  -1 is "higher" than -1.6.  As in, -1 is logically greater than -1.6.  To go lower the floor function would go to -2 which is logically less than -1.6.
Floor isn't trying to give you the number closest to zero, it's giving you the lowest bounding integer of a float.
In reply to Glen who commented:
Glen
01-Dec-2007 04:22
<?php
echo floor(1.6);  // will output "1"
echo floor(-1.6); // will output "-2"
?>
instead use intval (seems to work v5.1.6):
<?php
echo intval(1.6);  // will output "1"
echo intval(-1.6); // will output "-1"
?>

Contributed By: maikl

A correction to the funcion floor_dec from the user "php is the best".
If the number is 0.05999 it returns 0.59 because the zero at left position is deleted.
I just added a '1' and after the floor or ceil call remove with a substr.
Hope it helps.
function floor_dec(\$number,\$precision = 2,\$separator = '.') {
\$numberpart=explode(\$separator,\$number);
\$numberpart=substr_replace(\$numberpart,\$separator,\$precision,0);
if(\$numberpart>=0) {
\$numberpart=substr(floor('1'.\$numberpart),1);
} else {
\$numberpart=substr(ceil('1'.\$numberpart),1);
}
\$ceil_number= array(\$numberpart,\$numberpart);
return implode(\$separator,\$ceil_number);
}

PHP fmod() Function

What does fmod() do?

The PHP fmod() function will give you the floating point remainder (modulo) of the division of the arguments.

PHP fmod() Syntax

fmod ( float \$x , float \$y ) : float

PHP fmod() Parameters

1. x — The dividend

2. y — The divisor

PHP fmod() Return Value

The PHP fmod() function returns the floating point remainder of x/y

PHP fmod() Working Examples

1. Using fmod()

<?php
\$x = 5.7;
\$y = 1.3;
\$r = fmod(\$x, \$y);
// \$r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

PHP is_finite() Function

What does is_finite() do?

The PHP is_finite() function will finds whether a value is a legal finite number.

PHP is_finite() Syntax

is_finite ( float \$val ) : bool

PHP is_finite() Parameters

1. val — The value to check

PHP is_finite() Return Value

The PHP is_finite() function returns TRUE if val is a legal finite number within the allowed range for a PHP float on this platform, else FALSE.

PHP is_infinite() Function

What does is_infinite() do?

The PHP is_infinite() function will give you TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

PHP is_infinite() Syntax

is_infinite ( float \$val ) : bool

PHP is_infinite() Parameters

1. val — The value to check

PHP is_infinite() Return Value

The PHP is_infinite() function returns TRUE if val is infinite, else FALSE.

PHP is_nan() Function

What does is_nan() do?

The PHP is_nan() function will checks whether val is ‘not a number’, like the result of acos(1.01).

PHP is_nan() Syntax

is_nan ( float \$val ) : bool

PHP is_nan() Parameters

1. val — The value to check

PHP is_nan() Return Value

The PHP is_nan() function returns TRUE if val is ‘not a number’, else FALSE.

PHP is_nan() Working Examples

1. is_nan() example

<?php
// Invalid calculation, will return a
// NaN value
\$nan = acos(8);
var_dump(\$nan, is_nan(\$nan));
?>

Output of the above code:

float(NAN)
bool(true)

Additional Tips from Fellow Developers

Contributed By: darkangel

Nan/"not a number" is not meant to see if the data type is numeric/textual/etc..
NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.
The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part.
There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.

PHP max() Function

What does max() do?

The PHP max() function will give you the highest value in that array. If at least two parameters are provided, max() return the biggest of these values.

PHP max() Syntax

max ( array \$values ) : mixed
max ( mixed \$value1 [, mixed \$... ] ) : mixed

PHP max() Parameters

1. values — An array containing the values.

2. value1 — Any comparable value.

3. ... — Any comparable value.

PHP max() Return Value

The PHP max() function returns the parameter value considered “highest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.

PHP max() Working Examples

1. Example uses of max()

<?php
echo max(2, 3, 1, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5
// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello
// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1);    // hello
// With multiple arrays of different lengths, max returns the longest
\$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)
// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4
\$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)
// If both an array and non-array are given, the array will be returned
// as comparisons treat arrays as greater than any other value
\$val = max('string', array(2, 5, 7), 42);   // array(2, 5, 7)
// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below example, -10 is treated as TRUE in the comparison
\$val = max(-10, FALSE); // -10
// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
\$val = max(0, TRUE); // TRUE
?>

Important Points about PHP max() Function

1. Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Additional Tips from Fellow Developers

Contributed By: keith

The simplest way to get around the fact that max() won't give the key is array_search:
<?php
\$student_grades = array ("john" => 100, "sarah" => 90, "anne" => 100);
?>
This could also be done with array_flip, though overwriting will mean that it gets the last max value rather than the first:
<?php
?>
To get all the max value keys:
<?php
?>

Contributed By: costinu

Max(null, 0) = null
max(0, null) = 0

PHP min() Function

What does min() do?

The PHP min() function will give you the lowest value in that array. If at least two parameters are provided, min() return the smallest of these values.

PHP min() Syntax

min ( array \$values ) : mixed
min ( mixed \$value1 [, mixed \$... ] ) : mixed

PHP min() Parameters

1. values — An array containing the values.

2. value1 — Any comparable value.

3. ... — Any comparable value.

PHP min() Return Value

The PHP min() function returns the parameter value considered “lowest” according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and ‘abc’) the first provided to the function will be returned.

PHP min() Working Examples

1. Example uses of min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2
// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello
// Here we are comparing -1 < 0, so -1 is the lowest value
echo min('hello', -1);    // -1
// With multiple arrays of different lengths, min returns the shortest
\$val = min(array(2, 2, 2), array(1, 1, 1, 1)); // array(2, 2, 2)
// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 4 < 5
\$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
// If both an array and non-array are given, the array is never returned
// as comparisons treat arrays as greater than any other value
\$val = min('string', array(2, 5, 7), 42);   // string
// If one argument is NULL or a boolean, it will be compared against
// other values using the rules FALSE < TRUE and NULL == FALSE regardless of the
// other types involved
// In the below examples, both -10 and 10 are treated as TRUE in the comparison
\$val = min(-10, FALSE, 10); // FALSE
\$val = min(-10, NULL, 10);  // NULL
// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
\$val = min(0, TRUE); // 0
?>

Important Points about PHP min() Function

1. Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

PHP round() Function

What does round() do?

The PHP round() function will give you the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

PHP round() Syntax

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

PHP round() Parameters

1. val — The value to round.

2. precision — The optional number of decimal digits to round to.

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

PHP round() Return Value

The PHP round() function returns the value rounded to the given precision as a float.

PHP round() Working Examples

1. round() examples

<?php
var_dump(round(3.4));
var_dump(round(3.5));
var_dump(round(3.6));
var_dump(round(3.6, 0));
var_dump(round(1.95583, 2));
var_dump(round(1241757, -3));
var_dump(round(5.045, 2));
var_dump(round(5.055, 2));
?>

Output of the above code:

float(3)
float(4)
float(4)
float(4)
float(1.96)
float(1242000)
float(5.05)
float(5.06)

2. How precision affects a float

<?php
\$number = 1346.21;
var_dump(round(\$number, 2));
var_dump(round(\$number, 1));
var_dump(round(\$number, 0));
var_dump(round(\$number, -1));
var_dump(round(\$number, -2));
var_dump(round(\$number, -3));
var_dump(round(\$number, -4));
?>

Output of the above code:

float(1346.21)
float(1346.2)
float(1346)
float(1350)
float(1300)
float(1000)
float(0)

3. mode examples

<?php
echo 'Rounding modes with 9.5' . PHP_EOL;
var_dump(round(9.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(9.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_ODD));
echo 'Rounding modes with 8.5' . PHP_EOL;
var_dump(round(8.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(8.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_ODD));
?>

Output of the above code:

Rounding modes with 9.5
float(10)
float(9)
float(10)
float(9)
Rounding modes with 8.5
float(9)
float(8)
float(8)
float(9)

4. mode with precision examples

<?php
echo 'Using PHP_ROUND_HALF_UP with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_UP));
var_dump(round( 1.54, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.54, 1, PHP_ROUND_HALF_UP));
echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_DOWN));
var_dump(round( 1.54, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.54, 1, PHP_ROUND_HALF_DOWN));
echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_EVEN));
var_dump(round( 1.54, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.54, 1, PHP_ROUND_HALF_EVEN));
echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_ODD with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_ODD));
var_dump(round( 1.54, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.54, 1, PHP_ROUND_HALF_ODD));
?>

Output of the above code:

Using PHP_ROUND_HALF_UP with 1 decimal digit precision
float(1.6)
float(1.5)
float(-1.6)
float(-1.5)
Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
float(1.5)
float(1.5)
float(-1.5)
float(-1.5)
Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
float(1.6)
float(1.5)
float(-1.6)
float(-1.5)
Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
float(1.5)
float(1.5)
float(-1.5)
float(-1.5)

Changelog for PHP round() Function

5.3.0 — The mode parameter was introduced.

5.2.7 — The inner workings of round() was changed to conform to the C99 standard.

Additional Tips from Fellow Developers

Contributed By: takingsides

In my opinion this function lacks two flags:
- PHP_ROUND_UP - Always round up.
- PHP_ROUND_DOWN - Always round down.
In accounting, it's often necessary to always round up, or down to a precision of thousandths.
<?php
function round_up(\$number, \$precision = 2)
{
\$fig = (int) str_pad('1', \$precision, '0');
return (ceil(\$number * \$fig) / \$fig);
}
function round_down(\$number, \$precision = 2)
{
\$fig = (int) str_pad('1', \$precision, '0');
return (floor(\$number * \$fig) / \$fig);
}
?>

Contributed By: depaula

As PHP doesn't have a a native number truncate function, this is my solution - a function that can be usefull if you need truncate instead round a number.
<?php
/**
* Truncate a float number, example: <code>truncate(-1.49999, 2); // returns -1.49
* truncate(.49999, 3); // returns 0.499
* </code>
* @param float \$val Float number to be truncate
* @param int f Number of precision
* @return float
*/
function truncate(\$val, \$f="0")
{
if((\$p = strpos(\$val, '.')) !== false) {
\$val = floatval(substr(\$val, 0, \$p + 1 + \$f));
}
return \$val;
}
?>
Originally posted in http://stackoverflow.com/a/12710283/1596489

Contributed By: slimusgm

If you have negative zero and you need return positive number simple add +0:
\$number = -2.38419e-07;
var_dump(round(\$number,1));//float(-0)
var_dump(round(\$number,1) + 0);//float(0)

Contributed By: djcox99

I discovered that under some conditions you can get rounding errors with round when converting the number to a string afterwards.
To fix this I swapped round() for number_format().
Unfortunately i cant give an example (because the number cant be represented as a string !)
essentially I had round(0.688888889,2);
which would stay as 0.68888889 when printed as a string.
But using number_format it correctly became 0.69.

Contributed By: twan

If you'd only want to round for displaying variables (not for calculating on the rounded result) then you should use printf with the float:

<?php printf ("%6.2f",3.39532); ?>

This returns: 3.40 .

Contributed By: Anonymous

Here is function that rounds to a specified increment, but always up. I had to use it for price adjustment that always went up to \$5 increments.

<?php
function roundUpTo(\$number, \$increments) {
\$increments = 1 / \$increments;
return (ceil(\$number * \$increments) / \$increments);
}
?>

Rate this post —     (No Ratings Yet) Loading...

Author: Nitish Kumar 