将浮点四舍五入到红宝石中最接近的整数


69

如果我有一个49.967的浮点数,然后执行.to_i,它将把它切成49,这对我的磁盘空间分析来说是.967超过900mb的空间,这些空间将不会在显示中显示。

是否有将数字四舍五入到最接近的整数的函数,或者我必须像这样自定义它:

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


@glennmcdonald,您的链接已断开。这是2.20的新链接:ruby-doc.org/core-2.2.0/Float.html
奥斯丁,

1

Answers:


126

尝试Float.round

irb(main):001:0> 5.44.round
=> 5
irb(main):002:0> 5.54.round
=> 6
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.