将浮点数四舍五入到 ruby​​ 中最接近的整数 [英] Rounding a float to the nearest integer in ruby

查看:64
本文介绍了将浮点数四舍五入到 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

这篇关于将浮点数四舍五入到 ruby​​ 中最接近的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆