Math 函数
在线手册:中文 英文
PHP手册

round

(PHP 4, PHP 5)

round对浮点数进行四舍五入

说明

float round ( float $val [, int $precision ] )

返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零(默认值)。

Example #1 round() 例子

<?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
?>

Note: PHP 默认不能正确处理类似 "12,300.2" 的字符串。见字符串转换为数值

Note: precision 参数是在 PHP 4 中被引入的。

参见 ceil()floor()number_format()


Math 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 对浮点数进行四舍五入

用户评论:

mamadrood (02-Mar-2012 10:14)

In order to NOT round up/down the "precision", better use this function ;

<?php
function dont_touch_the_precision($val, $pre = 0)
{
    return (int) (
$val * pow(10, $pre)) / pow(10, $pre);
}

echo
round(0.164654651, 3); // 0.165
echo "\n";
echo
dont_touch_the_precision(0.164654651, 3); // 0.164

?>

qeremy [atta] gmail [dotta] com (23-Feb-2012 10:38)

In order to NOT round up/down the "precision", this function could use;

<?php
function dont_touch_the_precision($val, $pre = 0) {
   
$val = (string) $val;
    if (
strpos($val, ".") !== false) {
       
$tmp = explode(".", $val);
       
$val = $tmp[0] .".". substr($tmp[1], 0, $pre);
    }
    return (float)
$val;
}

echo
round(0.164654651, 3); // 0.165
echo "\n";
echo
dont_touch_the_precision(0.164654651, 3); // 0.164
?>

LT Workshop (21-Dec-2011 10:10)

<?php
/**
 * Normal Round Up Method
 *
 * @param double $val
 * @param int $precision
 * @return double
 */

function round_up ( $val, $precision ) {
   
$p = pow ( 10, $precision );
   
$a = $p * $val;
   
$b = ceil($a);
    if((
round($b - $a, 2) > 0.5)){
       
$b -= 1.0;
    }
    return
$b / $p;
}
?>

James Dudeck (08-Dec-2011 11:41)

Rounding decimal points

<?php
   
function rfloor($real,$decimals = 2) {
        return
substr($real, 0,strrpos($real,'.',0) + (1 + $decimals));
    }
   
    function
rceil($real,$decimals = 2) {
       
$newreal = substr($real, 0,strrpos($real,'.',0) + (1 + $decimals));
        if(
$real[strlen($newreal)] > 0) {
           
$newreal[strlen($newreal) - 1] += 1;
        }
        return
$newreal;
    }
   
    function
rround($real,$decimals = 2,$halfdown = FALSE) {
       
$newreal = substr($real, 0,strrpos($real,'.',0) + (1 + $decimals));
        if((
$halfdown == FALSE) && ($real[strlen($newreal)] = 5)) {
           
$newreal[strlen($newreal) - 1] += 1;
        }
        else if(
$real[strlen($newreal)] > 5) {
           
$newreal[strlen($newreal) - 1] += 1;
        }
        return
$newreal;
    }
?>

Usage:
rceil(12.12146321,2); //12.13 -- as long as the value is greater than 0, round up.
rfloor(12.12946321,2); //12.12 -- drop everything after the number of decimal places
rround(12.12546321,2); //12.13 -- round half up
rround(12.12546321,2,TRUE); //12.12 -- round half down

christian at deligant dot net (15-Sep-2011 09:24)

this function (as all mathematical operators) takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute!

<?php
$a
=3/4;
echo
round($a, 2); // 0.75

setlocale(LC_ALL, 'it_IT@euro', 'it_IT', 'it');
$b=3/4;
echo
round($b,2); // 0,75
?>

Anonymous (25-Feb-2011 05:08)

Round function with PHP_ROUND_HALF_UP conversion

<?php
function round_up ( $value, $precision ) {

   
$pow = pow ( 10, $precision );

    return (
ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow;

}

var_dump ( round_up ( 499.9440000046, 3 ) ); // float(499.945)
?>

cheezfan at gmail dot com (07-Feb-2011 02:39)

If you're confused about how precision works, these mean the same:

<?php
round
($string,$precision);
round($string*10^$precision);
?>

omnibus at omnibus dot edu dot pl (19-Nov-2010 10:26)

Beware strange behaviour if number is negative and precision is bigger than the actual number of digits after comma.

round(-0.07, 4);

returns

-0.07000000000000001

So if you validate it against a regular expression requiring the maximum amount of digits after comma, you'll get into trouble.

Anonymous (08-Oct-2010 12:07)

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);
}
?>

feha at vision dot to (27-Aug-2010 03:59)

Here is a short neat function to round minutes (hour) ...

<?php

function minutes_round ($hour = '14:03:32', $minutes = '5', $format = "H:i")
{
   
// by Femi Hasani [www.vision.to]
   
$seconds = strtotime($hour);
   
$rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
    return
date($format, $rounded);
}

?>

You decide to round to nearest minute ...
example will produce : 14:05

lossantis at ig dot com dot br (15-Jul-2010 03:02)

The PHP_ROUND_HALF_UP is unabled to less php 5.3, but I've a solution for this:

<?php echo 252 / 40; // 6.3 ?>

If I round this:

<?php echo round(252 / 40); // 6 ?>

But I like to enable result like PHP_ROUND_HALF_UP. I can do this:

<?php echo round((252/40) + 0.5); // 7 ?>

It's usefull to paginators ;)

hugues at zonereseau dot com (01-Jul-2010 08:45)

I had problem with round() function I didn't gave me the same result in windows or on a linux server :

<?php
round
(4.725, 2); // gave me 4.72 on linux
round(4.725, 2); // gave me 4.73 on windows
?>

The expected result was 4.73

Here my function to resolve my problem

<?php
function mround($number, $precision=0) {
   
   
$precision = ($precision == 0 ? 1 : $precision);   
   
$pow = pow(10, $precision);
   
   
$ceil = ceil($number * $pow)/$pow;
   
$floor = floor($number * $pow)/$pow;
   
   
$pow = pow(10, $precision+1);
   
   
$diffCeil     = $pow*($ceil-$number);
   
$diffFloor     = $pow*($number-$floor)+($number < 0 ? -1 : 1);
   
    if(
$diffCeil >= $diffFloor) return $floor;
    else return
$ceil;
}

echo
mround(4.725, 2); // Yes 4.73
?>

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 [sent to me by email, not posted here] 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 02: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 08: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);
}
?>

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.

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 04: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 01: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 (31-Jul-2008 12: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 (30-Jul-2008 12: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 08: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 12: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 02: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 01: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 01: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'.

(26-Aug-2003 12: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 08: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 01: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 01: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 10: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 05: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 10: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 02: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 .