views:

95

answers:

1

I am currently trying to round off a float number but i get an error message like: undefined method round_to for float 16.666667.. and my code for rounding off is

  option = [keys[count],    (((o.poll_votes.count.to_f)/@general_poll.poll_votes.count.to_f)*100).round_to(1)]

And what suprises me the most is that i have used this code at several places and is working just fine..but now is giving me errors.

thanks in advance.

+3  A: 

the method round_to does not exist anywhere in ruby core. Most likely this functionality was included in a library you were using before but have not required it in your current project. After a quick search it looks like this functionality is included in the Ruby Facets library.

gem install facets

Check this article to add this functionality yourself: http://www.hans-eric.com/code-samples/ruby-floating-point-round-off/

FTA:

With a little monkey patching we can add custom round off methods to the Float class.

class Float
  def round_to(x)
    (self * 10**x).round.to_f / 10**x
  end

  def ceil_to(x)
    (self * 10**x).ceil.to_f / 10**x
  end

  def floor_to(x)
    (self * 10**x).floor.to_f / 10**x
  end
end

------------------ snip 8<-------------------

Corban Brook
I have realized that there was nothing in the library, can you please just explain in detail how i can use this monkey patching?anyway thanks for the response.
Donald
Monkey patching is just a way of saying appending methods to an already defined class. If you add this code to your project it will extend Float and methods will be available.I checked out the facets gem and it seems they have 2 methods round_to and round_at. round_at mimics the code posted above.. sorry if this caused confusion.
Corban Brook