Round a ruby float up or down to the nearest 0.05

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

提交回复
热议问题