PHP 增长百分比栏

PHP grow percentage bar

我不确定如何用语言表达,但我会尽力而为。 所以我有一个号码。 $number = 201 例如。这个数字四舍五入到下一个百位。例如,300。我想显示我的进度条以显示 201/300。或者,如果 $number = 23,我希望进度条显示 23(满分 100)。或者 $number = 506,显示 506/600。

所以现在,我了解到 bootstrap 进度条按百分比运行。所以 100%。所以一切都很好,直到 $number 超过 100。因为它不能在 $number = 100 out of 200 的情况下工作,因为 100 会显示为 100%。

我很确定我需要的是一些简单的数学知识,但现在,我想不出该怎么做。

<div class="progress" style="margin-bottom:0px">
  <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="2" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em; width: <?php echo $number; ?>%;">
    <?php echo $number; ?>
  </div>
</div>

谢谢

编辑:这不是如何四舍五入到最接近的 10 的重复。这已经完成了。使用 ceil($number / 100) * 100;这个问题是关于如何让百分比栏显示 450 out of 500

其实很简单:您想将值四舍五入到最接近的 100,这可以使用 ceil($number / 100) * 100 来完成。在你达到 "max" 水平后,你可以计算比率:

<?php
  // Get the next closest 100
  $nextHundred = ceil($number / 100) * 100;

  // Calculate ratio against nextHundred
  $ratio = $number / $nextHundred * 100;
?>

按照这个逻辑,你会得到:

  • 23% 表示 23,因为它是使用 23÷100
  • 计算的
  • 90% 表示 450,因为它是使用 450÷500
  • 计算的

但是,如果你想450给你50%(因为你想把它评估为(450-400)÷(500-400)),你基本上是在求100的模:

// Calculate modulus
$ratio = $number % 100;

无论哪种情况,您都可以在逻辑中使用 $ratio 代替 $number。请记住,出于可访问性原因,您还应该更新 aria-valuenow。要在进度条中显示比率,您只需回显 $number.'/'.$nextHundred.

而不是使用 $ratio
<div class="progress" style="margin-bottom:0px">
  <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="<?php echo $ratio; ?>" aria-valuemin="0" aria-valuemax="100" style="min-width: 2em; width: <?php echo $ratio; ?>%;">
    <?php echo $number.'/'.$nextHundred; ?>
  </div>
</div>

这实际上使用基础数学更简单。收到的 int/float 值除以 int/float 百分比最大值,然后乘以 100。

例如200 人中的 50 人和 400 人中的 35 人

 50/200 * 100 = 25. (25%)
 35/400 * 100 = 8.75 (8.75%) 

所以只需使用:

$percentage = (($number / $max) * 100)

然后,如果您想通过字符串显示它,只需使用 $number 和 $max 作为您的 "x out of y" 百分比条。