module Rounder

Rounds any numeric value to any nearest multiple of the chosen step. Returns value of the same type as the input argument.

Constants

VERSION

Version of the gem

Public Instance Methods

ceil_to(step) click to toggle source

Rounds up to a multiple of the chosen step.

@example

101.ceil_to(10) # => 110

@param step [Numeric] chosen step. @return [Numeric]

# File lib/rounder/core.rb, line 26
def ceil_to(step)
  basic_rounding(step) do |result, step_decimal|
    result < self ? result + step_decimal : result
  end
end
floor_to(step) click to toggle source

Rounds down to a multiple of the chosen step.

@example

99.floor_to(10) # => 90

@param step [Numeric] chosen step. @return [Numeric]

# File lib/rounder/core.rb, line 13
def floor_to(step)
  basic_rounding(step) do |result, step_decimal|
    result > self ? result - step_decimal : result
  end
end
round_to(step) click to toggle source

Rounds to the nearest multiple of the chosen step.

@example

101.round_to(10) # => 100

@param step [Numeric] chosen step. @return [Numeric]

# File lib/rounder/core.rb, line 39
def round_to(step)
  basic_rounding(step)
end

Private Instance Methods

basic_rounding(step) { |result, step_decimal| ... } click to toggle source
# File lib/rounder/core.rb, line 45
def basic_rounding(step)
  check_argument_type(step)
  return self if step.zero?
  step_decimal = BigDecimal(step.abs.to_s)
  result       = step_decimal * (self / step_decimal).round
  result       = yield(result, step_decimal) if block_given?
  step.class == Integer ? result.to_i : result.to_f
end
check_argument_type(arg) click to toggle source
# File lib/rounder/core.rb, line 54
def check_argument_type(arg)
  error_message = 'This method accepts only numeric values'
  raise ArgumentError, error_message unless arg.is_a?(Numeric)
end