简体   繁体   中英

Percentage calculation, doesn't give the exact value

I have an issue with a progress bar formed by a table and an image as bar.

this is the table formation

<td><?php echo $img1; ?></td>
<td><?php echo $img2; ?></td>
<td><?php echo $img3; ?></td>
<td><?php echo $img4; ?></td>
<td><?php echo $img5; ?></td>

and this is the php code:

<?php
$value = 10000 //this value is obtained by SQL
$bar1 = 2600 //is the value of the first bar, obtained by SQL
$bar2 = 9950 //is the value of the second bar, obtained by SQL
$bar3 = 13010 //same as before
$bar4 = 17500 //same as before
$bar5 = 19500 //same as before

if($value > 0) && ($value < $bar1) {
$percent = ($value / $bar1) *100;
$bar1 = '<img src="progress.png" width="'.$percent.'" />';
}

if($value >= $bar1) {
$percent = '100';
$bar1 = '<img src="reached.png" width="'.$percent.'" />';
?>

And for the first bar is ok, work as intended, if the value is minor of $bar1 amount, then it show it as progress, if instead, it is higher than the $bar1 amount, it shows it as reached.

The Issues start with the other bars, taking an example the bar 3:

<?php 
if($value > $bar2) && ($value < bar3) {
$percent = ($value / $bar3) *100;
$bar3 = '<img src="progress.png" width="'.$percent.'" />';
}
>?

Obviosly the response of the percent is: 76 percent, and it almost full fill all the bar. The fact is the previous bar is setted as 9950, and the value is 10000, so on the $bar3 (which is 13010) should be showen something like (between 30 percent), and not 76 percent.

The purpose is simple:

When the $value, it fill the $bar1, then it moves on and starts filling the $bar2, if this one has been filled too, then it moves to the $bar3.. this until the $value is not enough anymore to fill or it reaches the last $bar5.

However, this is happening "wrong".

What I mistaken in this?

I solved the issue by changing the operation:

$bar3_reduced = $bar3 - $bar2;
$new = $value - $bar2; //detract from the value the previous bar amount
$percent = ($new / $bar3_reduced)*100;

So now it compares only the progress on the "new" bar, instead of counting them all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM