[icinga-checkins] icinga.org: icingaweb2-module-director/master: CustomVariableNumber: tolerant float comparison

git at icinga.org git at icinga.org
Thu Oct 6 18:47:26 CEST 2016


Module: icingaweb2-module-director
Branch: master
Commit: 2c071e215da88fb76f371ffae29cdbd38993ffc4
URL:    https://git.icinga.org/?p=icingaweb2-module-director.git;a=commit;h=2c071e215da88fb76f371ffae29cdbd38993ffc4

Author: Thomas Gelf <thomas at gelf.net>
Date:   Thu Oct  6 16:18:34 2016 +0000

CustomVariableNumber: tolerant float comparison

---

 .../CustomVariable/CustomVariableNumber.php        |   24 +++++++++++---------
 1 file changed, 13 insertions(+), 11 deletions(-)

diff --git a/library/Director/CustomVariable/CustomVariableNumber.php b/library/Director/CustomVariable/CustomVariableNumber.php
index 7816fa6..7c6703a 100644
--- a/library/Director/CustomVariable/CustomVariableNumber.php
+++ b/library/Director/CustomVariable/CustomVariableNumber.php
@@ -6,22 +6,25 @@ use Icinga\Exception\ProgrammingError;
 
 class CustomVariableNumber extends CustomVariable
 {
+    // Hint: 'F' is intentional, this MUST NOT respect locales
+    const PRECISION = '%.9F';
+
     public function equals(CustomVariable $var)
     {
         if (! $var instanceof CustomVariableNumber) {
             return false;
         }
 
-        // TODO: in case we encounter problems with floats we could
-        //       consider something as follows, but taking more care
-        //       about precision:
-        /*
-        if (is_float($this->value)) {
-            return sprintf($var->getValue(), '%.9F')
-                === sprintf($this->getValue(), '%.9F');
+        $cur = $this->getValue();
+        $new = $var->getValue();
+
+        // Be tolerant when comparing floats:
+        if (is_float($cur) || is_float($new)) {
+            return sprintf(self::PRECISION, $cur)
+                === sprintf(self::PRECISION, $new);
         }
-        */
-        return $var->getValue() === $this->getValue();
+
+        return $cur === $new;
     }
 
     public function getDbFormat()
@@ -59,8 +62,7 @@ class CustomVariableNumber extends CustomVariable
         if (is_int($this->value)) {
             return (string) $this->value;
         } else {
-            // Hint: this MUST NOT respect locales
-            return sprintf('%F', $this->value);
+            return sprintf(self::PRECISION, $this->value);
         }
     }
 }



More information about the icinga-checkins mailing list