Rounding a float to the nearest integer in ruby

Ruby

Ruby Problem Overview


If i have a float of 49.967 and I do .to_i it will chop it down to 49 which for my use of disk space analysis .967 is over 900mb of space that wont be accounted for in the displays.

Is there a function to round numbers to the nearest integer or would i have to define it my self like this:

class Float
  def to_nearest_i
    (self+0.5).to_i
  end
end

so that i could then do:

>> 5.44.to_nearest_i
=> 5
>> 5.54.to_nearest_i
=> 6

Ruby Solutions


Solution 1 - Ruby

Try Float.round.

irb(main):001:0> 5.44.round
=> 5
irb(main):002:0> 5.54.round
=> 6

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArcathView Question on Stackoverflow
Solution 1 - RubydetunizedView Answer on Stackoverflow