Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a ruby float up or down to the nearest 0.05

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?

like image 562
dotty Avatar asked Sep 10 '25 02:09

dotty


2 Answers

[2.36363636363636, 4.567563, 1.23456646544846, 10.5857447736].map do |x|
  (x*20).round / 20.0
end
#=> [2.35, 4.55, 1.25, 10.6]
like image 91
sepp2k Avatar answered Sep 13 '25 07:09

sepp2k


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
like image 41
Damian Avatar answered Sep 13 '25 07:09

Damian