【问题标题】:Yii2 less than evaluates to true at equalYii2 小于等于 true
【发布时间】:2017-05-30 11:59:10
【问题描述】:

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

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-&gt;FnGmin &lt; $this-&gt;fnut 计算结果为 true,但是如果我打印它们相等的值。例如。 FnGmin = 8.37fnut = 8.37 它是红色!但是有时该函数会返回正确的评估! FnGmin = 8.38fnut = 8.38 不是红色的!没有更多隐藏的小数位和四舍五入。到底是怎么回事?你能帮我么?我将不胜感激!

【问题讨论】:

    标签: php yii2 comparison-operators


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 2013-10-19
      • 2011-01-25
      • 1970-01-01
      • 2018-01-23
      • 2012-09-11
      • 1970-01-01
      • 2013-01-05
      相关资源
      最近更新 更多