title: Python round a float to nearest 0.05 or to multiple of another float
body: <p>I want to emulate <a href="https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.worksheetfunction.floor%28v=office.15%29.aspx" rel="nofollow noreferrer">this function</a>. I want to round a floating point number down to the nearest multiple of 0.05 (or generally to the nearest multiple of anything).</p>
  <p>I want this:</p>
  <pre><code>&gt;&gt;&gt; round_nearest(1.29, 0.05)
  1.25
  
  &gt;&gt;&gt; round_nearest(1.30, 0.05)
  1.30
  </code></pre>
  <p>I can do this:</p>
  <pre><code>import math
  
  def round_nearest(n, r):
      return n - math.fmod(n, r)
  
  &gt;&gt;&gt; round_nearest(1.27, 0.05)
  1.25  # Correct!
  
  &gt;&gt;&gt; round_nearest(1.30, 0.05)
  1.25  # Incorrect! Correct would be 1.30.
  </code></pre>
  <p>The incorrect answer above is presumably due to floating point rounding. I could put some special case check to see if the <code>n</code> is &quot;close enough&quot; to a multiple of <code>r</code> and not do the subtraction, and that would probably work, but is there a better way? Or is <a href="https://stackoverflow.com/a/9256018/223486">this strategy</a> the best option?</p>