Yii2小于等于的真值

时间:2017-05-30 11:59:10

标签: php yii2 comparison-operators

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

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评估为true,但是如果我打印它们等于的值。例如。 FnGmin = 8.37fnut = 8.37以及红色!但有时函数会返回正确的评估! FnGmin = 8.38fnut = 8.38它不是红色的!没有更多隐藏的小数位和舍入。到底是怎么回事?你能帮我么?我非常感谢!

1 个答案:

答案 0 :(得分:2)

我想这是因为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'] : [];