将红宝石上浮或下降至最接近的0.05 [英] Round a ruby float up or down to the nearest 0.05

查看:125
本文介绍了将红宝石上浮或下降至最接近的0.05的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  2.36363636363636 
4.567563
1.234566465448465
10.5857447736

如何让Ruby将这些数字向上(或向下)舍入到最接近的0.05?

解决方案

检查这个链接,我认为这是你需要的。
Ruby舍入 ($)

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 10 ** x
end

def ceil_to(x)
(self * 10 ** x).ceil.to_f / 10 ** x
end

f floor_to(x)
(self * 10 ** x).floor.to_f / 10 ** x
end
end


I'm getting numbers like

2.36363636363636
4.567563
1.234566465448465
10.5857447736

How would I get Ruby to round these numbers up (or down) to the nearest 0.05?

解决方案

Check this link out, I think it's what you need. Ruby rounding

class Float
  def round_to(x)
    (self * 10**x).round.to_f / 10**x
  end

  def ceil_to(x)
    (self * 10**x).ceil.to_f / 10**x
  end

  def floor_to(x)
    (self * 10**x).floor.to_f / 10**x
  end
end

这篇关于将红宝石上浮或下降至最接近的0.05的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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