Ruby Always Round Up

Ruby

Ruby Problem Overview


I feel like a crazy person. I'd like to round all fractions up to the nearest whole number.

For example, 67/30 = 2.233333333334. I would like to round that up to 3. If the result is not a whole number, I never want to round down, only up.

This is what I'm trying:

puts 67/30.to_f.ceil

Here are examples of what I'm looking for:

  • 67/30 = 3
  • 50/100 = 1
  • 2/2 = 1

Any ideas? Thanks much!

Ruby Solutions


Solution 1 - Ruby

The problem is that you're currently calling ceil on 30.to_f. Here's how Ruby evaluates it:

(67)/(30.to_f.ceil)
# .ceil turns the float into an integer again
(67)/(30.0.ceil)
# and now it's just an integer division, which will be 2
67/30 # = 2

To solve this, you can just add parenthesis:

puts (67/30.to_f).ceil  # = 3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrandonView Question on Stackoverflow
Solution 1 - RubyfivedigitView Answer on Stackoverflow