How to round an integer up to the nearest multiple of 'multiple' in Ruby

1 Answer

0 votes
#     roundUp(n, multiple)
#     --------------------
#     Rounds the integer n *up* to the nearest multiple of `multiple`.
#
#     Mathematically:
#         result = ceil(n / multiple) * multiple
#
#     We use integer arithmetic for efficiency:
#         (n + multiple - 1) / multiple  → smallest integer ≥ n/m

def round_up(n, multiple)
  if multiple <= 0
    # Defensive programming: avoid undefined behavior.
    # In real-world code, you'd throw or handle this differently.
    return n
  end

  # Efficient integer rounding up:
  ((n + multiple - 1) / multiple) * multiple
end

# main
puts "roundUp(53, 20)  = #{round_up(53, 20)}"
puts "roundUp(68, 30)  = #{round_up(68, 30)}"
puts "roundUp(7, 100)  = #{round_up(7, 100)}"
puts "roundUp(119, 100) = #{round_up(119, 100)}"
puts "roundUp(781, 100) = #{round_up(781, 100)}"
puts "roundUp(1026, 100) = #{round_up(1026, 100)}"
puts "roundUp(11689, 1000) = #{round_up(11689, 1000)}"


# run:
#
# roundUp(53, 20)  = 60
# roundUp(68, 30)  = 90
# roundUp(7, 100)  = 100
# roundUp(119, 100) = 200
# roundUp(781, 100) = 800
# roundUp(1026, 100) = 1100
# roundUp(11689, 1000) = 12000
#

 



answered Jul 22 by avibootz

Related questions

1 answer 252 views
...