【问题标题】:Why PHP returns false in if condition when array_sum() value is 1? [duplicate]为什么当 array_sum() 值为 1 时 PHP 在 if 条件下返回 false? [复制]
【发布时间】:2018-11-30 07:17:02
【问题描述】:

我面临一个奇怪的问题,数组的总和是 1,但是当我将它检查到 IF 条件时它返回 false。

$array = array
(
    0 => 0.237,
    1 => 0.318,
    2 => 0.215,
    3 => 0.06,
    4 => 0.069,
    5 => 0.053,
    6 => 0.048
);

if(array_sum($array) != 1){
    echo "It's not one";
} else {
    echo "It's one"; 
}

上面的代码返回 It's not one 而不是 It's one

【问题讨论】:

  • 因为浮点数学。
  • 我需要如何解决这个问题?我检查了 array_sum($arrays),它显示 1。
  • 取决于它需要有多准确。您可以使用 round()ceil()floor()bcmath 扩展名(以及更多),具体取决于您的要求。
  • 我需要检查必须为 1 的数组值的总和,并且我的数组是动态的。
  • 使用if ((string)array_sum($array) != 1)

标签: php array-sum


【解决方案1】:

试试这个解决方案

$sum=number_format(array_sum($array));
if($sum != 1){
    echo "It's not one";
} else {
    echo "It's one"; 
}

【讨论】:

    【解决方案2】:

    您无法在不四舍五入的情况下比较浮点值。 在这里查看更多>>http://php.net/manual/en/language.types.float.php

    你可以这样做,

    $array = array
    (
        0 => 0.237,
        1 => 0.318,
        2 => 0.215,
        3 => 0.06,
        4 => 0.069,
        5 => 0.053,
        6 => 0.048
    );
    
    if(round(array_sum($array)) != 1){
        echo "It's not one";
    } else {
        echo "It's one"; 
    }
    

    【讨论】:

    • 是的,但我需要检查我的值是否必须为 1。所以,我不能对它申请回合。
    • 在 php 中,floatval(1) == 1.0000000000000001。所以您的总和值必须至少四舍五入到小数点后 15 位
    • 在你的情况下,四舍五入到小数点后 3 位将是最好的解决方案round(array_sum($array), 3)
    • 它正在使用 if((float) trim(array_sum($array) != 1)
    • 太棒了。与舍入的唯一区别是您分两步进行。首先修剪它们。无论如何,这是工作,然后欢呼!
    猜你喜欢
    • 2014-07-03
    • 2014-12-29
    • 2011-05-22
    • 2018-02-24
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多