This functions return ceil($nb) if the double or float value is bigger than "$nb.5" else it's return floor($nb)
<?php
function arounds_int($nb) {
if(!is_numeric($nb)) {
return false;
}
$sup = round($nb);
$inf = floor($nb);
$try = (double) $inf . '.5' ;
if($nb > $try) {
return $sup;
}
return $inf;
}
?>
round
(PHP 4, PHP 5)
round — Rounds a float
Description
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.
Note: The precision parameter was introduced in PHP 4.
Parameters
- val
-
The value to round
- precision
-
The optional number of decimal digits to round to, defaults to 0
- mode
-
One of PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD.
Return Values
The rounded value
Examples
Example #1 round() examples
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
Example #2 mode() examples
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>
Changelog
| Version | Description |
|---|---|
| 5.3.0 | The mode parameter was introduced. |
See Also
- ceil() - Round fractions up
- floor() - Round fractions down
- number_format() - Format a number with grouped thousands
round
02-Nov-2009 01:52
25-Sep-2009 10:42
This function will let you round to an arbitrary non-zero number. Zero of course causes a division by zero.
<?php
function roundTo($number, $to){
return round($number/$to, 0)* $to;
}
echo roundTo(87.23, 20); //80
echo roundTo(-87.23, 20); //-80
echo roundTo(87.23, .25); //87.25
echo roundTo(.23, .25); //.25
?>
17-Sep-2009 04:24
Formats a number to the specified number of significant figures.
<?php
/**
* Formats numbers to the specified number of significant figures.
*
* @author Bevan Rudge, Drupal.geek.nz
*
* @param number $number
* The number to format.
* @param integer $sf
* The number of significant figures to round and format the number to.
* @return string
* The rounded and formatted number.
*/
function format_number_significant_figures($number, $sf) {
// How many decimal places do we round and format to?
// @note May be negative.
$dp = floor($sf - log10(abs($number)));
// Round as a regular number.
$number = round($number, $dp);
// Leave the formatting to format_number(), but always format 0 to 0dp.
return number_format($number, 0 == $number ? 0 : $dp);
}
?>
14-Sep-2009 04:40
Just a little fix of my previous round_up() function (^ is bitwise xor operator in PHP!):
<?
function round_up($val, $precision) {
return round($val + pow(10,-$precision-1), $precision);
}
?>
Sorry about any confusion this might have caused to anyone.
03-Sep-2009 09:12
For you folks who are still using PHP4, or just want their code to stay backward compatible, here's a dirty trick to simulate the PHP_ROUND_HALF_UP mode.
By default, round() will round down (PHP_ROUND_HALF_DOWN):
<?php
echo round(0.5); // gives 0
?>
To simulate round up, simply add the biggest rounded power of 10, like this:
<?php
echo round(0.5 + 0.1); // gives 1 instead of 0
echo round(1.45/10 + 0.001, 2); // gives 0.15 instead of 0.14
?>
This could be generalized:
<?php
function round_up($val, $precision) {
return round($val + 10^(-($precision+1)), $precision);
}
?>
25-Jun-2009 05:25
Note that the last anonymous one does NOT work for numbers such as (1.444, 2) -- it still returns 1.4
<?php
function roundPrecision($value, $precision=3 ){
// BAD CODE
$round = $precision - floor(log10(abs($value))) - 1;
// DON'T USE ME
return round($value, $round);
}
?>
Instead, Darkstream's works. Use that one.
30-Mar-2009 05:00
Function to round in increments I made:
<?php
function round_to($number, $increments) {
$increments = 1 / $increments;
return (round($number * $increments) / $increments);
}
?>
For example:
<?php
$n = 5.3;
echo round_to($n, 0.5); // 5.5
?>
Daniel.
23-Dec-2008 10:31
Precision rounding. Works for any value, including negative values, and values between 1 and 0.
<?php
function roundPrecision($value, $precision=3 ){
$round = $precision - floor(log10(abs($value))) - 1;
return round($value, $round);
}
?>
30-Oct-2008 07:36
Here's a quick gotcha:
I was fetching some data from a web service using cURL & SimpleXML and getting values like 28.75. I was then rounding these values but getting 28 instead of 29.
Turns out the values were strings, so round() would treat them as integers, and casting to an int drops off the decimals (like floor()).
So I had to do:
round( (double) $val );
HTH!
13-Oct-2008 12:16
Here is another method to round digits with precision support:
<?php
function roundDigits( $value, $precision=0 )
{
$precisionFactor = ($precision == 0) ? 1 : pow( 10, $precision );
return round( $value * $precisionFactor ) / $precisionFactor;
}
?>
Example:
echo roundDigits(1.859438,2) . "<br />"; // equals 1.86
echo roundDigits(1.444444,4); // equals 1.4444
Greetings, darki
01-Sep-2008 09:05
I dont think it is a bug as such but when rounding genrally you tend to only round from the digit after the precision you want.
The only way to get arround this is by rounding it twice with diffrent precisions:
<?php
$round1 = round(8.1246, 3); //8.125
$round2 = round($round1, 2); //8.13
echo $round2;
?>
30-Jul-2008 08:05
In case anyone has a problem like me ever, were you are doing very large stat calculations on a array and end up with floats with way to large of precision. A good way to round them all to N length is below.
<?php
public function recursiveRound(array &$arr, $precision)
{
foreach($arr as $key => $val) {
if(is_array($val)) {
$this->recursiveRound($arr[$key], $precision);
} elseif(is_float($val)) {
$arr[$key] = round($arr[$key], $precision);
}
}
return $arr;
}
?>
29-Jul-2008 08:59
I needed a round up function with precision which surprisingly did not exist (at least that I could see). This does the trick:
<?php
function roundUp( $value, $precision=0 )
{
// If the precision is 0 then default the factor to 1, otherwise
// use 10^$precision. This effectively shifts the decimal point to the
// right.
if ( $precision == 0 ) {
$precisionFactor = 1;
}
else {
$precisionFactor = pow( 10, $precision );
}
// ceil doesn't have any notion of precision, so by multiplying by
// the right factor and then dividing by the same factor we
// emulate a precision
return ceil( $value * $precisionFactor )/$precisionFactor;
}
?>
20-Apr-2008 04:09
My simple work around.
<?php
function my_round($value, $precision=0) {
return round(round($value*pow(10, $precision+1), 0), -1)/pow(10, $precision+1);
}
?>
16-Apr-2008 08:32
Excample :
<?php
function if_this_an_int($arg)
{
if(strlen($arg) > 0 && is_numeric($arg) && $arg > 0)
{
echo round($arg);
}
}
$test = 1.3;
echo if_this_an_int($test);
?>
You can use this function for any formular in your website, when you must to check if not empty or zero and it's a number
I hope you can need this.
29-Mar-2008 06:08
Here is basic function I sue to round file size. It gives as output text, so it's very easy to use it in your applications.
$SIZE is file size in MB.
function output is text.
<?php
function sizetotext($SIZE){
if ($SIZE>=1024){
$SIZE=round($SIZE/1024,2);
return $SIZE."GB";
}else{
if ($SIZE>=1){
return $SIZE."MB";
}else{
$SIZE=$SIZE*1000;
return "~".$SIZE."KB";
}
}
}
?>
27-Feb-2008 06:16
Remember kids that rounding a DB NULL will result in a 0 zero; test your NULLs!
12-Jan-2008 09:40
Please note that the format of this functions output also depends on your locale settings. For example, if you have set your locale to some country that uses commas to separate decimal places, the output of this function also uses commas instead of dots.
This might be a problem when you are feeding the rounded float number into a database, which requires you to separate decimal places with dots.
See it in action:
<?php
echo round('3.5558', 2);
setlocale(constant('LC_ALL'), 'et_EE.UTF-8');
echo '<br />'. round('3.5558', 2);
?>
The output will be:
3.56
3,56
05-Aug-2007 10:39
I'm sure its been done before, but here's my example of a round up function.
This function allows you to specify the number of decimal places to round up to.
Eg, when rounding up to 3 decimal places, this function adds 0.0005 to the original value and performs round(), or for 6 decimal places, adds 0.0000005 and performs round(), etc...
Hopefully some of you will find it useful:
<?php
function roundup ($value, $dp)
{
// Offset to add to $value to cause round() to round up to nearest significant digit for '$dp' decimal places
$offset = pow (10, -($dp + 1)) * 5;
return round ($value + $offset, $dp);
}
?>
Please post if you have any comments or improvements on this :-)
18-Mar-2007 01:31
I just found out then that even if you round a double (3.7) to an integer (4), it's data type remains as 'double'. So it's always good to use the settype() function when using the round() function to prevent any problems with your scripts.
28-Feb-2007 11:13
The function round numbers to a given precision.
<?php
function toFixed($number, $round=2)
{
$tempd = $number*pow(10,$round);
$tempd1 = round($tempd);
$number = $tempd1/pow(10,$round);
return $number;
}
echo round(5.555,2); //retunr 5.55 - I don't know why
echo toFixed(5.555,2); //return 5.56
?>
16-Oct-2006 09:15
the result of this function always depends on the underlying C function. There have been a lot of compiler bugs and floating-point precission problems involving this function. Right now the following code:
<?php
echo round(141.075, 2);
?>
returns:
141.07
on my machine.
So never really trust this function when you do critical calculations like accounting stuff!
Instead: use only integers or use string comparisons.
Instead of writing roundDown() and roundUp() functions in php, you might want to consider floor() and ceil(), as they are probably much, much faster.
13-Nov-2004 02:16
If you didn't want to use 'ceil()' or 'floor()' as it only rounds to a whole number u could do this:
<?php
$actual_value = 3.352;
$number = 0.01; //how many decimal places you want it to be
$temp1 = $actual_value * 2;
$temp2 = $temp1 + $number; //'+ $number' if rounding up '- $number' if rounding down
$temp3 = $temp2 / 2;
$new_value = round($temp3, 2);
echo $new_value; // 3.36
?>
19-Jul-2004 08:21
Better is:
<?php
$actual_value = 3.45; // 3.45
$half_round = round(($actual_value*2), 0)/2; // 3.5
?>
or
<?php
$actual_value = 3.45; // 3.45
$temp1 = $actual_value * 2; // 6.9
$temp2 = round($temp1, 0); // 7
$half_round = $temp2 / 2 // 3.5
?>
NOT
<?php
$actual_value = 3.45; // 3.45
$temp1 = $actual_value * 2; // 6.9
$temp2 = round($actual_value, 0); // 7
$half_round = $temp2 / 2 // 3.5
?>
12-Jan-2004 04:45
To round any number to a given number of significant digits, use log10 to find out its magnitude:
<?php round($n, ceil(0 - log10($n)) + $sigdigits); ?>
Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:
<?php
// $exp = currency decimal places - 0 for Yen/Won, 2 for most others
$dp = ceil(0 - log10($n)) + $sigdigits;
$display = number_format($amount, ($exp>$dp)?$exp:$dp);
?>
This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.
Many have thus far mentioned problems encountered when trying to add a small fuzz factor to a number such as 1.499999999. This is the way I get around that problem using , allbeit probably less efficient than assuming a small possiblitiy for error:
<?php
$numberToRound = 1.5;
//Convert to string.
$numberToRound = "$numberToRound";
//iff number ends in a "5", add fuzz
if (eregi("$5", $pages)) $pages += .000001;
$round = round($pages, 0);
?>
07-Aug-2003 04:30
The round() function may indeed work properly with half-values (eg. 1.5), but this little method will give you peace of mind. Add some "fuzz" to your function with a miniscule delta value.
<?php
$delta = 0.00001;
$x = round($x+$delta);
?>
This is fine, unless $x has a value of 1.49999 ... if you worried about that, use this method instead:
<?php
if(($x-floor($x))==0.5){
$x+=$delta;
}
$x = round($x);
?>
you can change your "optimistic" delta into a "pessimistic" delta by subtracting instead of adding.
Cheers,
Ian Ring
18-Jun-2003 09:39
The function below regards a higher number of digits for rounding as the number of digits you want to round! At least it rounds a Value to the number of digits you want to:
<?php
function MyRound($iValue, $iDigits, $iPrecision){
$iDigits = intval($iDigits);
$iPrecision = intval($iPrecision);
if($iDigits > $iPrecision){ $iPrecision = $iDigits; }
for($i = $iPrecision; $i >= $iDigits; $i--){
$iValue = round($iValue, $i);
} // for($i = $iPrecision; $i >= $iDigits; $i--) -- END
return $iValue;
}
?>
12-May-2003 09:08
<?php
// Rounding to the nearest fifth
// or any other increment you wish...
$percent = "48";
$num = round($percent/5)*5;
echo $num;
// returns 50
$percentt = "47";
$numm = round($percentt/5)*5;
echo $numm;
// returns 45
?>
23-Oct-2002 06:06
for a poll, if you want to have 100% and not 99 or 99.99 % you can do that :
<?php
round( number_format( (($individual_result*100)/$total_result), 2), 1);
?>
20-Aug-2002 01:10
because of some site-effects between round() and modulo, therfore the result is not exactly at every time ...
another way ( and without site-effects) of getting 0.05 increments for currencies, f.e. swiss francs:
<?php
$res = (round(20*$chf))/20;
echo $res;
?>
with kind regards
14-Aug-2002 06:15
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.
ex:
<?php
round(1241757, -3); // 1242000
RoundSigDigs(1241757, 3); // 1240000
?>
Works on negative numbers too. $sigdigs should be >= 0
<?php
function RoundSigDigs($number, $sigdigs) {
$multiplier = 1;
while ($number < 0.1) {
$number *= 10;
$multiplier /= 10;
}
while ($number >= 1) {
$number /= 10;
$multiplier *= 10;
}
return round($number, $sigdigs) * $multiplier;
}
?>
15-May-2000 10:51
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 .
