Round a ruby float up or down to the nearest 0.05

后端 未结 9 1672
日久生厌
日久生厌 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.

    0 讨论(0)
  • 2020-12-29 04:45

    I know that the question is old, but I like to share my invention with the world to help others: this is a method for rounding float number with step, rounding decimal to closest given number; it's usefull for rounding product price for example:

    def round_with_step(value, rounding)
      decimals = rounding.to_i
      rounded_value = value.round(decimals)
    
      step_number = (rounding - rounding.to_i) * 10
      if step_number != 0
        step = step_number * 10**(0-decimals)
        rounded_value = ((value / step).round * step)
      end
    
      return (decimals > 0 ? "%.2f" : "%g") % rounded_value
    end
    
    # For example, the value is 234.567
    #
    # | ROUNDING | RETURN | STEP
    # | 1        | 234.60 | 0.1
    # | -1       | 230    | 10
    # | 1.5      | 234.50 | 5 * 0.1 = 0.5
    # | -1.5     | 250    | 5 * 10  = 50
    # | 1.3      | 234.60 | 3 * 0.1 = 0.3
    # | -1.3     | 240    | 3 * 10  = 30
    
    0 讨论(0)
  • 2020-12-29 04:46

    To get a rounding result without decimals, use Float's .round

    5.44.round
    => 5
    
    5.54.round
    => 6
    
    0 讨论(0)
  • 2020-12-29 04:52
    [2.36363636363636, 4.567563, 1.23456646544846, 10.5857447736].map do |x|
      (x*20).round / 20.0
    end
    #=> [2.35, 4.55, 1.25, 10.6]
    
    0 讨论(0)
  • 2020-12-29 04:55

    It’s possible to round numbers with String class’s % method.

    For example

    "%.2f" % 5.555555555
    

    would give "5.56" as result (a string).

    0 讨论(0)
  • 2020-12-29 04:56

    Check this link out, I think it's what you need. Ruby rounding

    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
    
    0 讨论(0)
提交回复
热议问题