I\'m getting numbers like
2.36363636363636
4.567563
1.234566465448465
10.5857447736
How would I get Ruby to round these numbers up (or dow
Here's a general function that rounds by any given step value:
place in lib:
lib/rounding.rb
class Numeric
# round a given number to the nearest step
def round_by(increment)
(self / increment).round * increment
end
end
and the spec:
require 'rounding'
describe 'nearest increment by 0.5' do
{0=>0.0,0.5=>0.5,0.60=>0.5,0.75=>1.0, 1.0=>1.0, 1.25=>1.5, 1.5=>1.5}.each_pair do |val, rounded_val|
it "#{val}.round_by(0.5) ==#{rounded_val}" do val.round_by(0.5).should == rounded_val end
end
end
and usage:
require 'rounding'
2.36363636363636.round_by(0.05)
hth.