Round a ruby float up or down to the nearest 0.05

后端 未结 9 1676
日久生厌
日久生厌 2020-12-29 04:43

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

9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 04:43

    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.

提交回复
热议问题