Yii2 小于等于等于

Yii2 less than evaluates to true at equal

我有一个函数来检查属性值是否小于另一个:

public function getFnGminGrFnotKlFnut() {
    if ($this->FnGmin) {
        return $this->FnGmin > $this->fnot || $this->FnGmin < $this->fnut ? ['class' => 'danger'] : [];
    } else {
        return [];
    }
}

查看:

[
    'attribute' => 'FnGmin',
    'contentOptions' => function ($model) {return $model->fnGminGrFnotKlFnut;},
],

$this->FnGmin < $this->fnut 的计算结果为真,但是如果我正在打印它们相等的值。例如。 FnGmin = 8.37fnut = 8.37 并且它是 红色 !不过有时候函数returns评价正确!通过 FnGmin = 8.38fnut = 8.38 它不是红色的!不再有隐藏的小数位和四舍五入。到底是怎么回事?你能帮我么?我将不胜感激!

我猜这是因为 php 的浮点精度。我猜你已经计算了一些使用的值。

例如:

$x = 8 - 6.4;  // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true
//PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()
var_dump(round($x, 2) == round($y, 2)); // this is true

已经有几个答案:

PHP - Getting a float variable internal value

Set precision for a float number in PHP

在你的情况下使用这样的东西:

// set some wanted floating point precision which is higher that your used float numbers e.g. 3 
$precision = 3;


return round($this->FnGmin, $precision) > round($this->fnot, $precision)  || round($this->FnGmin, $precision)  < round($this->fnut, $precision) ? ['class' => 'danger'] : [];