Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cap and round number in ruby

I would like to "cap" a number in Ruby (on Rails).

For instance, I have, as a result of a function, a float but I need an int.

I have very specific instructions, here are some examples:

If I get 1.5 I want 2 but if I get 2.0 I want 2 (and not 3)

Doing number.round(0) + 1 won't work.

I could write a function to do this but I am sure one already exists.

If, nevertheless, it does not exist, where should I create my cap function?

like image 462
0x26res Avatar asked May 19 '09 19:05

0x26res


People also ask

How do you round a number 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.

How do I limit decimal places 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) ).

How do you round a float to 2 decimal places in Ruby?

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.


1 Answers

Try ceil:

 1.5.ceil => 2  2.0.ceil => 2 
like image 187
gnovice Avatar answered Oct 12 '22 23:10

gnovice