title: PostgreSQL floating point arithmetic and types
body: <p>I have a Postgres-driven application which rounds quantities to the next (not nearest) 4th decimal place. So, 0.00341 becomes 0.0035. </p>
  
  <p>In implementing it, I came upon a situation where 0.0012 <em>even</em> is being rounded up to 0.0013, even though it shouldn't; it's 0.0012 even. In fact, even <code>ceil()</code> agrees, at first glance:</p>
  
  <pre><code>postgres=&gt; SELECT ceil(((0.0012) * 10000)) / 10000;
          ?column?        
  ------------------------
   0.00120000000000000000
  (1 row)
  </code></pre>
  
  <p>We know that there is no arbitrary precision introduced:</p>
  
  <pre><code>postgres=&gt; SELECT (ceil(((0.0012) * 10000)) / 10000) = 0.0012;
   ?column? 
  ----------
   t
  (1 row)
  </code></pre>
  
  <p>Yet, when the figure 0.0012 is arrived at by way of a <em>computation</em>, the situation changes:</p>
  
  <pre><code>postgres=&gt; SELECT (12::double precision / 60) * 0.006;
   ?column? 
  ----------
     0.0012
  (1 row)
  
  postgres=&gt; SELECT ((12::double precision / 60) * 0.006) = 0.0012;
   ?column? 
  ----------
   f
  (1 row)
  </code></pre>
  
  <p>It would appear that the computed 0.0012 is greater than actual 0.0012:</p>
  
  <pre><code>postgres=&gt; SELECT ((12::double precision / 60) * 0.006) &gt; 0.0012;
   ?column? 
  ----------
   t
  (1 row)
  </code></pre>
  
  <p>Predictably, this leads the rounding mechanism to round 0.0012 "up" to 0.0013, which is obviously wrong if the expression evaluates to 0.0012 even:</p>
  
  <pre><code>postgres=&gt; SELECT ceil(((12::double precision / 60) * 0.006) * 10000) / 10000;
   ?column? 
  ----------
     0.0013
  (1 row)
  </code></pre>
  
  <p>So, clearly I'm missing something here about how the expression is evaluated and/or how the data types involved are cast. There's additional precision introduced that shouldn't be there.</p>
  
  <p>Any help would be appreciated!</p>