开发者

Rounding a float to the nearest integer in ruby

开发者 https://www.devze.com 2023-01-28 00:11 出处:网络
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 900开发者_如何学编程mb of space that wont be accounted for in the displays.

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 900开发者_如何学编程mb 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


Try Float.round.

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

精彩评论

暂无评论...
验证码 换一张
取 消