How to cap and round number in ruby

Viewed 37319

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?

5 Answers

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

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

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?

Related