Useful Numeric Functions in PHP
There are many functions related to numbers.like Useful Numeric Functions in PHP ,Mathematical Functions in PHP Here are a few of the most common and useful:
abs() :
Returns the absolute value of the number.
Syntax:
1 |
abs(number); |
Example;
1 2 3 4 5 6 |
<?php echo abs(5)."<br />"; echo abs(-5)."<br />"; echo abs(8.5)."<br />"; echo abs(-8.5)."<br />"; ?> |
Output Will be :
5
5
8.5
8.5
pi() :
Return the value of pi.
Syntax:
1 |
pi(); |
Example :
1 2 3 |
<?php echo(pi()); ?> |
Output will be
3.1415926535898
round() :
Rounds a number to nearest integer.
Syntax
1 |
round($number, $precision, $mode); |
$number : Number which you wnat to round
$precision : Optional Parameter. It specifies the number of decimal digits to round to. The default value of this parameter is zero.
$mode : Rounding mode.
Possible values :
PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php echo round(8.4)."<br />"; //Output will be 8 echo round(8.5)."<br />"; //Output will be 9 echo round(8.5,0)."<br />"; //Output will be 9 echo round(10.4556,2)."<br />"; //Output will be 10.46 echo round(0.45)."<br />"; //Output will be 0 echo round(0.65)."<br />"; //Output will be 1 echo round(-1.45)."<br />"; //Output will be 1 ?> |
sqrt() :
Retruns the sqaure root of a number.
Syntax :
1 |
sqrt(<em>number</em>); |
Example :
1 2 3 4 5 6 7 8 9 10 |
<?php echo sqrt(1); //Output will be 1 echo sqrt(2); //Output will be 4 echo sqrt(5); //Output will be 25 echo sqrt(-); //Output will be NAN ?> |