While working on a research tool for my work I have noticed that my ruby solution rounds differently then the original c# .net code. It was not in every but about 10 percent of my tests failed due to the different rounding schemes.

Ruby uses the Symmetric Arithmetic Rounding while C# .net uses the Gaussian rounding otherwise known as the Banker’s routing.

I have looked for a quick solution for Ruby but Google did not return a result I could immediately use. I have found a javascript solution which I translated to Ruby.

Additionally I have added a “decimal” parameter to specify the precision of rounding.

Here is the code:

class Numeric
  def _round(val)
    sign = val < 0 ? -1 : 1
    return (val.abs.round * sign) if (val.abs - val.abs.floor) != 0.5
    return (val.abs.ceil  * sign) if val.abs.floor % 2 == 1
    return (val.abs.floor * sign)
  end

  def gaussian_round(decimals = 0)
    return (_round(self * (10**decimals))/((10**decimals).to_f))
  end
end

Ref: Javascript Gaussian Rounding Example
Ref: Wikipedia article on rounding