title: Accurate floating point arithmetic in JavaScript
body: <p>I am creating number spinner widget in JavaScript to essentially mimic the number field in webkit.</p>
  
  <p>When you change the number, it needs to check to see if the value is not only within the accepted range, but also that it's in step:</p>
  
  <pre><code>&lt;input type="number" min="0" max="100" step="1" /&gt;
  </code></pre>
  
  <p>If a user enters <code>5.5</code> the field will truncate this to the closest step lower than the value, which in this case is <code>5</code>.</p>
  
  <p>For a step of <code>2</code>, if the user entered <code>5.5</code>, the result would be <code>4</code>.</p>
  
  <p>The equation I was planning on using for this calculation looks like this:</p>
  
  <pre><code>...code...
  _checkStep: function (val) {
      val ret,
          diff,
          moddedDiff;
      diff = val - this._min;
      moddedDiff = diff % this._step;
      ret = val - moddedDiff;
      return ret;
  },
  //set elsewhere
  _min,
  _step,
  ...more code...
  </code></pre>
  
  <p>Although for testing purposes, you could simply use this:</p>
  
  <pre><code>function checkStep(val, min, step) {
      var ret,
          diff,
          moddedDiff;
      diff = val - min;
      moddedDiff = diff % step;
      ret = val - moddedDiff;
      return ret;
  }
  </code></pre>
  
  <p>This works great for integers and larger values, however I've run into issues with decimals due to how JavaScript handles floating point numbers.</p>
  
  <p>For example:</p>
  
  <pre><code>checkStep(0.5, 0, 0.1) //returns 0.4, 0.5 is expected
  </code></pre>
  
  <p>In analyzing each line, it turns out that <code>0.5 % 0.1</code> in JavaScript returns <code>0.09999999999999998</code>.</p>
  
  <p>What can be done to make this function more accurate*?</p>
  
  <hr>
  
  <p>*accurate being that it works for increments of <code>0.01</code> and up.</p>