→ Round number to specific number of decimal places in Ruby → → →

The easy way is to extend Float class by adding round_to method with precision parameter.

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

Output:

>> 1.3456.round_to 1
=> 1.3
>> 1.3456.round_to 2
=> 1.35
>> 1.3456.round_to 3
=> 1.346

Created on 16 May 2009