Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Always Round Up

Tags:

ruby

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!

like image 287
Brandon Avatar asked Aug 28 '14 07:08

Brandon


People also ask

Does Ruby round up or down?

Ruby Language Numbers Rounding Numbers The round method will round a number up if the first digit after its decimal place is 5 or higher and round down if that digit is 4 or lower.

How do you round up in Ruby?

The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter ( round() ) or with a parameter ( round(n) ). n here means the number of decimal places to round it to.

How do you round down numbers in Ruby?

Ruby | Numeric round() function The round() is an inbuilt method in Ruby returns a number rounded to a number nearest to the given number with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.


1 Answers

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 
like image 87
fivedigit Avatar answered Sep 22 '22 09:09

fivedigit