PHP Doku:: Rundet einen Fließkommawert - function.round.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzMathematische ErweiterungenMathematische FunktionenMathematische Funktionenround

Ein Service von Reinhard Neidl - Webprogrammierung.

Mathematische Funktionen

<<rand

sin>>

round

(PHP 4, PHP 5)

roundRundet einen Fließkommawert

Beschreibung

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

Rundet den Parameter val auf die mit precision angegebene Anzahl von Nachkommastellen ab. precision kann dabei auch null (Vorgabewert) oder negativ sein. So wird bei einer Stellenzahl von -1 wird z.B. auf volle Zehner gerundet.

Hinweis: PHP behandelt Strings wie "12,300.2" standardmäßig nicht korrekt. Siehe String-Konvertierung.

Hinweis: Die Angabe der gewünschten Stellenzahl precision ist seit PHP 4 möglich.

Parameter-Liste

val

Der zu rundende Wert

precision

Die optionale gewünschte Anzahl Nachkommastellen, Vorgabewert ist 0

mode

PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN oder PHP_ROUND_HALF_ODD.

Rückgabewerte

Der gerundete Wert

Beispiele

Beispiel #1 round()-Beispiele

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

Changelog

Version Beschreibung
5.3.0 Der Parameter mode wurde hinzugefügt.

Siehe auch


38 BenutzerBeiträge:
- Beiträge aktualisieren...
omnibus at omnibus dot edu dot pl
19.11.2010 11: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
8.10.2010 1: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.08.2010 16: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.07.2010 16: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
1.07.2010 21: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
5.01.2010 17: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
2.11.2009 17: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.09.2009 15: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.09.2009 21: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.06.2009 22: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.03.2009 22: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.12.2008 2: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.10.2008 23: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.10.2008 17: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
1.09.2008 14: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.07.2008 1: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.07.2008 1: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.04.2008 9: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.04.2008 13: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.03.2008 22: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.02.2008 22:16
Remember kids that rounding a DB NULL will result in a 0 zero;  test your NULLs!
martinr at maarja dot net
13.01.2008 0: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
6.08.2007 3: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.03.2007 5: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.02.2007 15: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.10.2006 14: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.01.2006 21: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.11.2004 18: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.07.2004 14: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.01.2004 20: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.08.2003 1: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
7.08.2003 21: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.06.2003 14: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.05.2003 2: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.10.2002 23: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.08.2002 18: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.08.2002 23: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.05.2000 3: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 .



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)