我有一个表单,用户可以在其中输入浮点值。我将这些值发布到php脚本,并比较用户输入的数字是否在某些值之间。如果我发布一个整数,则无论数字是否超出边界,比较都返回true。如果我输入浮点数,则无论数字是否在边界内,比较都会失败。我不是傻瓜,我在c ++中进行浮点比较,我知道如何做if(float1> = float2)返回false ...
这是我的代码:
//loading the helper
$val = Loader::helper('synerciel_form','synerciel_client');
//adding the fields to the inputs array for validation
$val->between('isolation_des_murs_peripheriques', 2.8, null, t($between.'Isolation des murs
pèriphèriques'), true, false);
//助手类
class SynercielFormHelper extends ValidationFormHelper {
const VALID_BETWEEN = 7;
const VALID_FLOAT = 7;
private $min;
private $max;
private $includeLow;
private $includeHigh;
public function between($field, $min, $max, $errorMsg, $includeLow = true, $includeHigh = true) {
$const = SynercielFormHelper::VALID_BETWEEN;
$this->min = $min;
$this->max = $max;
$this->includeLow = $includeLow;
$this->includeHigh = $includeHigh;
$this->addRequired($field, $errorMsg, $const);
}
...
public function test() {
$between = new ValidationNumbersBetweenHelper();
if (!$between->between($this->data[$field], $this->min, $this->max, $this->includeLow, $this->includeHigh)) {
$this->fieldsInvalid[] = $f;
}
}
我的验证方法(我相信这里很棘手)
class ValidationNumbersBetweenHelper {
public function between($data, $min = null, $max = null, $includeLow = true, $includeHigh = true) {
if ($min && $includeLow) {
if (!($data >= $min))
return false;
} else if ($min) {
if (!($data > $min))
return false;
}
if ($max && $includeHigh) {
if (!($data <= $max))
return false;
} else if ($max) {
if (!($data < $max))
return false;
}
return true;
}
}
答案 0 :(得分:0)
检查警告信息http://php.net/manual/en/language.operators.comparison.php
您可以使用BC数学函数http://php.net/manual/en/function.bccomp.php
$status = bccomp($left, $right);
if ($status == 0) {
echo 'equal';
} else if ($status > 0) {
echo 'left bigger than right';
} else {
echo 'right bigger than left';
}
希望这有帮助
答案 1 :(得分:0)
尝试隔离麻烦的代码。将验证功能放入独立的PHP文件中并在那里进行测试。请尝试$max
检查$min
和!== null
0
,因为false
也是!
。您可以撤消逻辑并删除所有>=
。 (例如,将<
更改为{{1}}),而不是“不大于或等于”,您可以“少于”