0x26res
0x26res

Reputation: 13952

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?

Upvotes: 41

Views: 38028

Answers (5)

gnovice
gnovice

Reputation: 125874

Try ceil:

 1.5.ceil => 2
 2.0.ceil => 2

Upvotes: 79

meso_2600
meso_2600

Reputation: 2136

.ceil is good, but remember, even smallest value in float will cause this:

a = 17.00000000000002
17.0
a.ceil
18

Upvotes: 11

Patrick McDonald
Patrick McDonald

Reputation: 65471

How about number.ceil?

This returns the smallest Integer greater than or equal to number.

Be careful if you are using this with negative numbers, make sure it does what you expect:

1.5.ceil      #=> 2
2.0.ceil      #=> 2
(-1.5).ceil   #=> -1
(-2.0).ceil   #=> -2

Upvotes: 11

Sparr
Sparr

Reputation: 7732

float.ceil is what you want for positive numbers. Be sure to consider the behavior for negative numbers. That is, do you want -1.5 to "cap" to -1 or -2?

Upvotes: 2

Pesto
Pesto

Reputation: 23901

Use Numeric#ceil:

irb(main):001:0> 1.5.ceil
=> 2
irb(main):002:0> 2.0.ceil
=> 2
irb(main):003:0> 1.ceil
=> 1

Upvotes: 6

Related Questions