Home | MySQL Russian Manual | MySQL Manual | Apache HTTP Server Rus Documentation | Apache HTTP Server Documentation | downloads | faq

search for in the  Language: Russian


round

(PHP 4, PHP 5)

roundRounds a float

Description

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

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.

Parameters

val

The value to round

precision

The optional number of decimal digits to round to.

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.60);      // 4
echo round(1.955832);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.0452);    // 5.05
echo round(5.0552);    // 5.06
?>

Example #2 mode() examples

<?php
echo round(9.50PHP_ROUND_HALF_UP);   // 10
echo round(9.50PHP_ROUND_HALF_DOWN); // 9
echo round(9.50PHP_ROUND_HALF_EVEN); // 10
echo round(9.50PHP_ROUND_HALF_ODD);  // 9

echo round(8.50PHP_ROUND_HALF_UP);   // 9
echo round(8.50PHP_ROUND_HALF_DOWN); // 8
echo round(8.50PHP_ROUND_HALF_EVEN); // 8
echo round(8.50PHP_ROUND_HALF_ODD);  // 9
?>

Changelog

Version Description
5.3.0 The mode parameter was introduced.
5.2.7 The inner workings of round() was changed to conform to the C99 standard.

See Also


User Contributed Notes
round
edgarmveiga at gmail dot com
05-Jan-2010 04:58
Trying to simulate the toPrecison function of Javascript, I have obtained this method. Any sugestions or revisions would be appreciated:

<?php

  
/**
     * Rounding to significant digits ( just like JS toPrecision() )
     *
     * @number <float> value to round
     * @sf <int> Number of significant figures
     */
   
public function toPrecision($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.
         
$numberFinal = round($number, $dp);

         
//If the original number it's halp up rounded, don't need the last 0
         
$arrDecimais=explode('.',$numberFinal);
          if(
strlen($number) > strlen($numberFinal) && $dp > strlen($arrDecimais[1])) {
               
$valorFinal=sprintf("%.".($dp-1)."f", $number);
          }
          else {
              
//Leave the formatting to format_number(), but always format 0 to 0dp.
               
$valorFinal=str_replace(',', '', number_format($numberFinal, 0 == $numberFinal ? 0 : $dp));
          }

         
// Verify if needs to be represented in scientific notation
         
$arrDecimaisOriginal=explode('.',$number);
          if(
sizeof($arrDecimaisOriginal)>=2) {
              return (
strlen($arrDecimaisOriginal[0])>$sf)?
                                                           
sprintf("%.".($sf-1)."E", $valorFinal) :
                                                           
$valorFinal;
          }
          else {
              return
sprintf("%.".($sf-1)."E", $valorFinal);
          }
    }
?>
Anonymous
02-Nov-2009 04:52
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;
    }
?>
michaeldnelson dot mdn at gmail dot com
25-Sep-2009 01: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
?>
Bevan
17-Sep-2009 07: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);
}
?>
microberto at yahoo dot com
25-Jun-2009 08: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.
mydanielsmile+phpnet at gmail dot com
30-Mar-2009 08: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.
Anonymous
24-Dec-2008 01: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);
}
?>
Montoya
30-Oct-2008 10: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!
darkstream777 at gmx dot net
13-Oct-2008 03: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
Chris
01-Sep-2008 12: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;
?>
chris at chrisstockton dot org
30-Jul-2008 11: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;
    }
?>
Darryl Kuhn
29-Jul-2008 11: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;
}
?>
alveda at pinoywebsys dot com
20-Apr-2008 07: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);
}
?>
ThOmAs
16-Apr-2008 11: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.
admin at studio-gepard dot pl
29-Mar-2008 09: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";
    }
  }

}
?>
skinnepa at hotmail dot com
27-Feb-2008 09:16
Remember kids that rounding a DB NULL will result in a 0 zero;  test your NULLs!
martinr at maarja dot net
12-Jan-2008 11: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
mark at customcartons dot com dot au
06-Aug-2007 01: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 :-)
tom at crysis-online dot com
18-Mar-2007 04: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.
chafy at alo dot bg
28-Feb-2007 02: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
?>
maxteiber at gmail dot com
16-Oct-2006 12: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.
27-Jan-2006 08:41
Instead of writing roundDown() and roundUp() functions in php, you might want to consider floor() and ceil(), as they are probably much, much faster.
martin at chinese-monkey dot com
13-Nov-2004 05: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
?>
red at aztec dot sk
19-Jul-2004 12: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
?>
terry at scribendi dot com
12-Jan-2004 07: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'.
25-Aug-2003 11:12
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);
?>
ianring (at) golden.net
07-Aug-2003 07: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
ralf dot schreijer at smc dot uni-muenster dot de
18-Jun-2003 12: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;
}
?>
Oromian
13-May-2003 12: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
?>
tichoux at charlevoix dot net
23-Oct-2002 09: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);
?>
kt at netspirit dot ch
20-Aug-2002 04: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
php at silisoftware dot com
14-Aug-2002 09: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;
}
?>
twan at ecreation dot nl
16-May-2000 01: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 .
 

 
credits | contact