将浮点数四舍五入到 ruby​​ 中最接近的整数

问题描述:

如果我有一个 49.967 的浮点数并且我执行 .to_i 它将把它削减到 49,这对于我使用的磁盘空间分析来说 .967 是超过 900mb 的空间,不会在显示中考虑.

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

这样我就可以:

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

尝试 Float.round.

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