views:

704

answers:

6

Hi,

I would like to "cap" a number in ruby (on rails). For instance I have has a result of a function a float but I need an int.

I have very specific instructions, here are examples: if I get 1.5 I want 2 if but if I get 2.0 I want 2 (and not 3)

so doing number.round(0) + 1 it won't work.

I could write this function but, I sure it already exists.

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

+4  A: 

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
Patrick McDonald
+4  A: 

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
Pesto
+3  A: 

Try ceil:

 1.5.ceil => 2
 2.0.ceil => 2
gnovice
+1  A: 

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?

Sparr
+1  A: 

Don't get it. I see in the core documentation that there is a round() method in the Float class.

flt.round => integer

Rounds flt to the nearest integer. Equivalent to:

def round
    return (self+0.5).floor if self > 0.0
    return (self-0.5).ceil  if self < 0.0
    return 0    
end

1.5.round      #=> 2    (-1.5).round   #=> -2
Leonardo Herrera
1.2.round => 1, OP wants the answer 2
Patrick McDonald
A: 

Thanks for the answer,

Negative numbers are out of the scope so ceil will work for me

jules