Skip to content

Instantly share code, notes, and snippets.

@tal
Created February 17, 2010 00:19
Show Gist options
  • Select an option

  • Save tal/306122 to your computer and use it in GitHub Desktop.

Select an option

Save tal/306122 to your computer and use it in GitHub Desktop.
module RoundTo
# def self.included(klass)
# if klass.instance_method(:round)
# klass.class_eval do
# begin
# remove_method :round
# rescue NameError
# end
# end
# super
# else
# raise NoMethodError, 'no round method found'
# end
# end
# A more versitile rounding function that rounds to an arbitrary number
# of decimil places
def round_to(places = 0)
unless Integer === places
raise TypeError, "argument places has to be an Integer"
end
if places < 0
max_places = -Math.log(self.abs + 1) / Math.log(10)
raise ArgumentError, "places has to be >= #{max_places.ceil}" if max_places > places
end
t = self
f = 10.0 ** places
t *= f
if t >= 0.0
t = (t + 0.5).floor
elsif t < 0.0
t = (t - 0.5).ceil
end
t /= f
t.nan? ? self : t
end
end
class ::Float # :nodoc:
unless method_defined?(:round_to)
include RoundTo
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment