0

我面临一个奇怪的问题,数组的总和为 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

4

2 回答 2

1

您无法在不四舍五入的情况下比较浮点值。在这里查看更多>> 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"; 
}
于 2018-11-30T07:27:29.957 回答
1

试试这个解决方案

$sum=number_format(array_sum($array));
if($sum != 1){
    echo "It's not one";
} else {
    echo "It's one"; 
}
于 2018-11-30T07:25:43.853 回答