title: Rounding to specific number of digits in Haskell
body: <p>I am trying to make a function to round a floating point number to a defined length of digits. What I have come up with so far is this:</p>
  
  <pre class="lang-hs prettyprint-override"><code>import Numeric;
  
  digs :: Integral x =&gt; x -&gt; [x] &lt;br&gt;
  digs 0 = [] &lt;br&gt;
  digs x = digs (x `div` 10) ++ [x `mod` 10]
  
  roundTo x t = let d = length $ digs $ round x &lt;br&gt;
                    roundToMachine x t = (fromInteger $ round $ x * 10^^t) * 10^^(-t)
                in roundToMachine x (t - d)
  </code></pre>
  
  <p>I am using the <code>digs</code> function to determine the number of digits before the comma to optimize the input value (i.e. move everything past the comma, so <code>1.234</code> becomes <code>0.1234 * 10^1</code>)</p>
  
  <p>The <code>roundTo</code> function seems to work for most input, however for some inputs I get strange results, e.g. <code>roundTo 1.0014 4</code> produces <code>1.0010000000000001</code> instead of <code>1.001</code>.</p>
  
  <p>The problem in this example is caused by calculating <code>1001 * 1.0e-3</code> (which returns <code>1.0010000000000001</code>)</p>
  
  <p>Is this simply a problem in the number representation of Haskell I have to live with or is there a better way to round a floating point number to a specific length of digits?</p>