Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

round

(PHP 3, PHP 4, PHP 5)

round -- Округляет число типа float

Описание

float round ( float val [, int precision] )

Возвращает округлённое значение val с указанной точностью precision (количество цифр после запятой). Последняя может быть отрицательной или нулём (по умолчанию).

Пример 1. Примеры функции round()

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

Замечание: PHP по умолчанию не может правильно обрабатывать строки типа "12,300.2". Для подробностей см. Разд. Преобразование строк в числа в Гл. 11.

Замечание: параметр precision был добавлен в PHP 4.

См. также: ceil(), floor() и number_format().



sin> <rand
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
round
KingIsulgard
29-Oct-2007 06:23
[quote]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 :-) [/quote]

This can be much more efficient:
<?php
function roundup ($value, $dp)
{
    return
ceil($value*pow(10, $dp))/pow(10, $dp);
}

function
rounddown ($value, $dp)
{
    return
floor($value*pow(10, $dp))/pow(10, $dp);
}
?>

Much cleaner, isn't it ;)?
thawee from thailand
10-Oct-2007 09:41
my round function
function rounding($n,$d){
    $base=intval($n);
    $n=number_format($n,25);
    $dotpos=strpos($n,".");
    $strlen=strlen($n);
    $b= substr($n,$dotpos+1,$strlen-$dotpos);
    $j=1;
    $p=0;
    for($i=strlen($b);$i>$d;$i--){
                $c=substr($b,-$j,1)+$p;
        if($c<5){
            $p=0;
        }else{
            $p=1;
        }
        $j++;
    }
 return $base+((substr($b,0,$d)+$p)/pow(10,$d));
}
xploded at lycos.com
04-Sep-2007 09:31
to mark at customcartons dot com dot au

found your roundup very useful, the only problem is if the value passed is 0.00 as it roundsup to 0.01 which may not be desired.

I modified the return statement to:

return ($value>0) ? round($value+$offset,$dp) : '0.00';

regards
James
Secret at secret dot com
23-Aug-2007 10:26
Round down..

A very simple way to round down is the following..

$numbera=41;
$numberb=3;

$sum=$numbera/$numberb;

echo $sum;   // Will give 13.66666.....

$rounddownsum=(int)($numbera/$numberb);

echo $rounddownsum;   // Will give 13    ;o)

If you wana round decimals simply multiply the variables with 10...100...1000 or whatever before performing this action.. Then divide back after calculations.. then ex.

$numbera=41;
$numberb=3;

$sum=$numbera/$numberb;

$sum=(int)($sum*1000);

$sum=$sum/1000;

echo $sum;   // Will give 13.666

Hope that helps someone... ;o)
mark at customcartons dot com dot au
05-Aug-2007 06: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 :-)
Pascal Hofmann
04-Aug-2007 11:21
The function from Felix Schwarz returns wrong results for values near 0. bccomp should be called with param $scale.

function bcround ($number, $decimals, $precision) {
    $precision_add = str_repeat("5",$precision);
    if (bccomp($number,0, $decimals+$precision) > 0) {
        return (bcadd (bcadd ($number, "0.".str_repeat("0",$decimals).$precision_add, $decimals+$precision), 0, $decimals));
    }
    else {
        return (bcadd (bcsub ($number, "0.".str_repeat("0",$decimals).$precision_add, $decimals+$precision), 0, $decimals));
    }
}
smithaapc at NOSPAM dot yahoo dot com
26-Jul-2007 03:44
round() is broken, plain and simple. The solution must take into account all of the digits of a given number during rounding. Truncating the number before the rounding eliminates valuable information. Consider:
  myRound(12.4444444443, 2) = 12.45 ... not quite.

Try this out instead:
  function trueRound($value, $figs=1) {
    if(is_numeric($value) && is_int($figs) && $figs > 0) {
// must adjust $figs down 1 for computing significant figures
      $figs--;
// $prec ensures all of the original digits are included in the sprintf format
      $prec = strpos($value, '.') === false ? strlen($value)-1 : strlen($value)-2;
      $sci = sprintf('%.'.$prec.'e', $value);
      list($sig, $mant) = explode('e', $sci);
// $base includes all of the significant digits, $test contains all the remaining digits
      list($base, $test) = explode('.', $sig * pow(10, $figs));
// All 4's on the left side of $test will not be significant in the rounding
      $test = preg_replace('/^4+/', '', $test);
// The first digit in $test that is not a 4 will determine the direction of the rounding
      $test = preg_replace('/^(\d)\d+/', '$1', $test);
      if($test > 4) {
// If the digit is > 4, then simply round up by adding 1 ...
        $base += 1;
      }
// ... then simply adjust the decimal point
      $value = $base * pow(10, $mant-$figs);
    }
      return($value);
  }

Note this function rounds up to a number of significant figures (all digits) rather than significant digits (digits after the decimal point). Rounding down could be easily accomplished by passing a switch along with the other parameters.

Mike
lex_63de at yahoo dot de
26-Jun-2007 06:33
Here is my little round function. Works nice on php 4.3.11 and 5.0.5

printf("0.285 - %s <br> ",round(0.285,2));      // incorrect result 0.28
printf("1.285 - %s <br> ",round(1.285,2));      // correct result 1.29
printf("1.255 - %s <br><br>",round(1.255,2));   // incorrect result 1.25

printf("0.285 - %s <br> ",myRound(0.285,2));    // incorrect result 0.29
printf("1.285 - %s <br> ",myRound(1.285,2));    // incorrect result 1.29
printf("1.255 - %s <br> ",myRound(1.255,2));    // incorrect result 1.255

function myRound($value,$round=2)
{
    $value *= pow(10.0,$round);
    $value  = floor(floatval($value + 0.6));
    $value /= pow(10.0,$round);

    return($value);
}
bitbrains at yahoo dot com
22-Jun-2007 06:59
Surprisingly, the round() cannot work with 1.255,

echo round(1.255, 2);    echo "<BR>";// 1.25
pjm at pehjota dot com
27-Apr-2007 05:01
In response to maxteiber at gmail dot com, regarding rounding 141.075 to 2 decimal places:

I can justify your computer for rounding it to 141.07. It's following a rounding rule similar to the "significant figures" rules in science. Try rounding 141.0751 or 141.0756.
tom at crysis-online dot com
17-Mar-2007 09: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.
15-Mar-2007 02:11
With regard to chafy at alo dot bg's not just previous; if the number 5.555 is displayed with sufficient precision (more than about 16 digits) it will probably turn out to have been stored as something like 5.554999999....9997, which would round down to 5.55.

Floating-point numbers should ALWAYS be regarded as being a little bit fuzzy. It's a consequence of the fact that they're stored in binary but humans want them displayed in decimal: you can't write one-tenth exactly as a binary expansion any more than you can write one-seventh exactly as a decimal one.

See the warning note on the floating-point type page.
chafy at alo dot bg
28-Feb-2007 06:13
The function round numbers to a given precision.

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
pokusman at gmail dot com
30-Jan-2007 07:06
<php?

function RoundPrice($Price) {
 $diff = $Price - floor($Price);
 if ($diff<=0.25) {
  $Price = floor($Price) + 0.25;
 };
 if ($diff>0.25 && $diff<=0.5) {
  $Price = floor($Price) + 0.5;
 };
 if ($diff>0.5 && $diff<=0.75) {
  $Price = floor($Price) + 0.75;
 };
 if ($diff>0.75) {
  $Price = floor($Price) + 1;
 };
 return $Price;
}

$Price = "369.68";
$NewPrice = RoundPrice($Price);  //369.75

echo "Old price:
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571