【问题标题】:Round Percentages PHP圆形百分比 PHP
【发布时间】:2013-07-15 16:34:51
【问题描述】:

我目前正在将两个值相除,以便从我的应用程序的实际计数和总计数中获得百分比。

我正在使用以下公式:

echo ($fakecount / $totalcount) * 100;

这给了我一个类似的值:79.2312313。我更喜欢 79% 这样的值。

我尝试了以下方法:

echo round($fakecount / $totalcount) * 100; 

这似乎无法正常工作。

有什么建议吗?

【问题讨论】:

  • 在圆内添加* 100:echo round($fakecount / $totalcount * 100);

标签: php variables math echo divide


【解决方案1】:

你需要在四舍五入之前乘以 100,而不是之后:

echo round($fakecount * 100 / $totalcount);

您正在计算$fakecount / $totalcount,它将是一个介于 0 和 1 之间的数字,然后将其四舍五入,得到 0 或 1,然后乘以 100,得到 0 或 100 作为您的百分比。

【讨论】:

    【解决方案2】:

    试试,

    echo (int)($fakecount * 100 / $totalcount + .5);
    

    这是因为如果小数部分是>= .5,加 0.5 会使整数部分加 1

    或者,

    round ($fakecount * 100 / $totalcount); 
    

    请注意,我在除法前乘以 100 以更好地保持精度。

    【讨论】:

    • 投射到int 与floor() 相同。使用round() 获取最接近的值。
    • @rjmunro 我的将返回与 round() 相同的值,因为我在类型转换之前添加了 0.5 :)
    • 抱歉,没发现。您确定转换为 int 的性能比使用 round() 的性能要好到足够的余量以比额外的加法更快吗?
    • @rjmunro:我不确定运行时性能。但并非所有语言都有 round() 函数,但在添加 0.5 后转换为 int 是所有语言的好方法。如果是关于运行时,我认为差异可以忽略不计,因为圆形函数必须做类似的事情(我不知道round()如何对数字进行四舍五入)
    【解决方案3】:
    echo intval(($fakecount / $totalcount) * 100); 
    

    或者你可以使用

    echo floor(($fakecount / $totalcount) * 100);  //Round down
    

    或者

    echo ceil(($fakecount / $totalcount) * 100);  // Round Up
    

    【讨论】:

    • intval() 与 floor() 相同。使用round()
    【解决方案4】:

    使用 round() 函数

    echo round(($fakecount / $totalcount) * 100);
    

    http://php.net/manual/en/function.round.php

    你可以使用的还有

    • ceil() - 向上舍入分数
    • floor() - 向下舍入分数

    【讨论】:

      【解决方案5】:

      不...

      有很多方法可以做到这一点。

      $mypercent = ($fakecount / $totalcount) * 100;
      

      记住..这将首先运行 (xxx) 内部的内容,然后* 100。

      之后……

      echo round($mypercent);
      

      如果你愿意,你也可以使用很多规则......

      <i>if ($value < 10) {
          $value = floor($value);
      } else {
          $value = round($value);
      }</i>
      

      不要忘记查看其他命令,也许你会需要它。

      ceil() - 向上取整分数

      floor() - 向下舍入分数

      =)

      【讨论】:

        猜你喜欢
        • 2015-06-03
        • 2019-08-22
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        • 2021-11-27
        相关资源
        最近更新 更多