title: Checking doubles for equality and Sonar issues
body: <p>We are checking the quality of our code using Sonar, and Sonar found code which compares a float or double for equality with a constant value like this:</p>
  
  <pre><code>if (x == 0.0) { … }
  </code></pre>
  
  <p>The value the variable is compared with (<code>0.0</code>) is constant, and in case the variable can be equal to this value, the value also isn't computed but only set via a constant.  This is typically used to check whether a variable hasn't been set yet or is still at initialization state, e. g. <code>-1.0</code> might be used for "not yet set" in cases where the value can only be positive.</p>
  
  <p>So, since these values are never <em>computed</em> but only <em>set from constants</em>, the Sonar complaint is not useful for us.  Only for computed values (or fractured ones which are not precisely representable as floats or doubles) a complaint about a test for equality makes sense.</p>
  
  <p>The question I have now is:  What is the best practice to change the code so that Sonar does not complain about this anymore?</p>
  
  <p>I see several options:</p>
  
  <ol>
  <li>Extract the "test-for-unset" into a special test function; but that would only reduce the number of occurrences (to 1), not the issue in general.</li>
  <li>Mark the code for Sonar to ignore it with a special decorator.  But we would like to avoid using such decorators.</li>
  <li>Hide the comparison behind sth like <code>(0.0 &lt;= x &amp;&amp; x &lt;= 0.0)</code> or <code>!(x != 0.0)</code> (which currently seems to be okay for Sonar).</li>
  <li>Calling <code>Double.doubleToRawLongBits()</code> to compare the bits of the values like this: <code>(Double.doubleToRawLongBits(x) != Double.doubleToRawLongBits(0.0))</code>.</li>
  <li>Other ideas?</li>
  </ol>
  
  <p>None of these solutions I really like and I thought, maybe, there is a better one out there I can't think of.</p>