【问题标题】:PHP: Max and Min returning incorrect resultsPHP:Max 和 Min 返回不正确的结果
【发布时间】:2012-07-04 01:33:09
【问题描述】:

我确定这是因为最后的“g”,但这是我尝试计算百分比百分比时的场景和结果。我总是想将 2 个数字中的最大值除以最小值。

$item1 = "200.00g";
$item2 = "50.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "400%"

$item1 = "100.00g";
$item2 = "5.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "2000%"

PROBLEM RESULT:
$item1 = "8.00g";
$item2 = "14.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "57%"
// I am expecting (14.00g / 8.00g)*100 = "175%"

【问题讨论】:

  • 嗯,你知道你在比较两个字符串,对吧?
  • 顺便说一句,第二个 sn-p 给了我 5% 而不是 2000%。没错,因为"5.00g""100.00g" 大。

标签: php max percentage min


【解决方案1】:

这是类型转换;

$item1 = "8.00";
$item2 = "14.00";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";

结果将是 175%

【讨论】:

    【解决方案2】:

    如果您想在数学运算中使用字符串,并且您知道该单元在您的示例中放置在末尾,您可以将变量转换为浮点数:

    $item1_numeric = (float) $item1;
    

    但显然,在变量/数据库中将值和单位分开会更好。

    【讨论】:

      【解决方案3】:

      使用:substr($item1, 0, -1) instade of $item1, substr($item2, 0, -1) instade of $item2 when you do round.

      你不能用 round() 比较 2 个字符串。

      编辑:如果 $item1 = "200g",ma 解决方案是可以的,但如果 $item1 = "200.00g" 你需要删除 "."在 round() 之前,例如 pregreplace。

      【讨论】:

        【解决方案4】:

        哦,YAPHPB - 也是我最喜欢的一个。虽然是写在the Doc:

        When [max()] given a string it will be cast as an integer when comparing.
        

        ...这只是部分事实:如果至少有一个比较值是数字或数字字符串。

        否则所有字符串都将被比较为字符串:每个字符串的前 {0} 个字符将被比较,然后是 {1},然后是 {2}...等等。

        所以基本上这就是这里发生的事情:

        echo max("200.00g", "50.00g"); // 50.00g, as '5' > '2'
        echo max("200.00g", 50);       // "200.00g", as it gets converted to int (become 200)
        

        这更疯狂:

        echo max("200.00g", "1000.00"); // "200.00g", as '2' > '1'
        echo max("200.00", "1000.00");  // "1000.00", as we tried to help you, no, really!
        

        知道numeric概念的人实际上可以预测后一个结果:当两个字符串都是纯数字时,它们在比较时会转换为数字。尽管如此,我发现这种行为至少可以说是不可靠的。

        底线:如果您需要比较数字,请比较数字,句号。 PHP 中的类型转换可能会变得非常混乱——当你最不期待的时候,它会咬你一口。 )

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-11
          • 2016-02-06
          • 2017-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-28
          相关资源
          最近更新 更多