Mark D
Mark D

Reputation: 326

Display percentage as progress

Assuming the following

  1. I have n objects in a list
  2. The objects are processed sequentially
  3. I want to display percentage complete whenever it crosses a certain amount

For example,

I have 2204 objects once it has processed 221 objects I want it to display 10%, then once it has processed 441 objects I want it to display 20%. Essentially so that I have a guideline of where the queue is at.

Writing this in php I had the following:

$i = 0;
$total = 2204 // result of getTotal();

foreach (range ($i, $total) as $i ) {
    //do some irrelevant processing
    if (($i/$total*100)%10 == 0) {
        echo number_format(($i/$total*100),0)."% done.\n";
    }
}

However my result set is less than desirable, I get the following as output:

0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
0% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.
1% done.

How would I accomplish this?

Upvotes: 0

Views: 184

Answers (3)

Cwissy
Cwissy

Reputation: 2156

my 2p answer would be to use a check variable

<?php
$i = 0;
$total = 2204; // result of getTotal()
$boundary=10;

foreach (range ($i, $total) as $i ) {
    //do some irrelevant processing
    $ii=intval(($i/$total)*100);
    if($ii>=$boundary){
        echo $boundary . "% done.\n";
        $boundary+=10;
    }
}

?>

Upvotes: 1

putvande
putvande

Reputation: 15213

$i = 0;
$total = 2204;

foreach (range ($i, $total) as $i ) {
    if ($i % floor($total/100) == 0) {
        echo number_format(($i/$total*100),0)."% done.\n";
    }
}

If you want it only each 10% (10,20,30...100) and not to include the 0 you could do :

$i = 0;
$total = 2204;

foreach (range ($i, $total) as $i ) {
    if ($i % floor($total/10) == 0 && $i > 0) {
        echo number_format(($i/$total*100),0)."% done.\n";
    }
}

Upvotes: 1

user1647708
user1647708

Reputation: 457

There is another problem I see with the logic you have here:

Since you are incrementing through this list by +1 you will not get exact 10%, 20%. For example when I do following:

foreach (range ($i, $total) as $i ) {
    echo $i/$total."\n";
}

you will see

0.19555353901996
0.19600725952813
0.1964609800363
0.19691470054446
0.19736842105263
0.1978221415608
0.19827586206897
0.19872958257713
0.1991833030853
0.19963702359347
0.20009074410163
0.2005444646098
0.20099818511797
0.20145190562613

You will probably want to round these off after multiplying by 100 and maintain a separate array where you will check to see if you have already displayed these values.

Sample program:

foreach (range ($i, $total) as $i ) {
    $val = round($i/$total*100)%10;
    $num = number_format(($i/$total*100),0);
if ($val == 0) {
    if(!in_array($num, $check)){
            $check[] =  $num;
            echo $num."% done.\n";
    }
}
}
?>

Upvotes: 1

Related Questions