1

How can I round up to the next hundred? Using Ruby 2.3.2.

48 -> 100 52 -> 100 112 -> 200

Tried 48.round(-2) but that rounds down. Trialed some BigDecimal values, but that got me nowhere.

Rich_F
  • 1,830
  • 3
  • 24
  • 45
  • Searching Google for "round number to next hundred" returns a number of hits, including some on SO, which help explain it such as http://stackoverflow.com/q/19621455/128421, http://stackoverflow.com/q/8866046/128421 – the Tin Man Dec 06 '16 at 23:16
  • 3
    Another way: `def roundup(n) 100*(1+((n-1)/100)) end; roundup(248) #=> 300; roundup(400) #=> 400; roundup(-240) #=> -200; roundup(-200) #=> -200`. – Cary Swoveland Dec 06 '16 at 23:26
  • Tin Man, several items on Google, whilst INCLUDING "Ruby", ran me into nothing but dead ends. It's why I included the version number here. Also, Ruby is not Javascript and has different methods and approaches. Same with Python. – Rich_F Dec 07 '16 at 10:49

2 Answers2

14

Divide by 100 first then multiply back.

(48/100.0).ceil * 100
Alejandro C.
  • 3,771
  • 15
  • 18
0

Use Integer#ceil/Float#ceil, saying that you want it to round to two places before the comma:

48.ceil(-2)

This isn't available in Ruby 2.3.0, but it is in Ruby >= 2.4.0.

Richard Möhn
  • 712
  • 7
  • 15
  • @Sujay, do you like this better? The accepted answer is right for Ruby 2.3.0, but nowadays there is a better way to round up to the next hundred. – Richard Möhn Aug 26 '21 at 21:48