views:

981

answers:

4

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?

Thanks

+5  A: 

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

Damian
Thanks for the link! the methods work perfectly.
dotty
Nice link. Answer would be better with a summary, though, so it can stand on it's own, especially since the linked code doesn't do exactly what the OP asks, i.e., round to the nearest 0.05, but rounds to a particular decimal place.
tvanfosson
+8  A: 
[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]
sepp2k
Darn, you beat be me by a couple of seconds! +1 from me, although I had a slight different version in mind.
Swanand
+2  A: 

Try 'nearest 5 cents' in Google. Heaps of results. Some of them relevant.

pavium
+2  A: 

In general the algorithm for “rounding to the nearest x” is:

round(x / precision)) * precision

Sometimes is better to multiply by 1 / precision because it is an integer (and thus it works a bit faster):

round(x * (1 / precision)) / (1 / precision)

In your case that would be:

round(x * (1 / 0.05)) / (1 / 0.05)

which would evaluate to:

round(x * 20) / 20;

I don’t know any Python, though, so the syntax might not be correct but I’m sure you can figure it out.

Bombe
In order to get decimals divide by 20.0 -> round(x * 20) / 20.0;
baijiu