round to function for ruby float class

17 September 2009 | 3:25 pm by codeboxer

I found this on a blog post somewhere, and it works really well. If you need to round your decimals to precision, this is your friend. It's a method extension for the standard float class in Ruby on Rails. Just save it into your lib/ folder as whatever you want, and 'require' it in as needed - like so:

  require 'float_helper'

I called it 'float_helper.rb'.

Behold:

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

used here to great effect as a simple round to integer:

  unaccounted_sales = x["value"].to_f.round_to(0)

but you can specify the precision as you like.

Enjoy!

Recommend Me




My Site Links

Screenshots are featured above. If you visit gmgpulse, you may login as demo/demo.

Rockstar Television


© 2008-10 Krister Axel and codeboxer.com