Let’s say you need to round to half numbers in Ruby, because you are making a rating system and want to display half stars for the ratings (1, 1.5, 2, 2.5, etc..). You want the following output when you are trying to round to the half fraction:

round_to_half( 1.6 )
=> 1.5

round_to_half( 1.7 )
=> 1.5

round_to_half( 1.8 )
=> 2.0

round_to_half( 2.1)
=> 2.0

round_to_half( 2.3 )
=> 2.5

etc…..

It is much simpler than I anticpated. You just need to multiply by the the inverse of the fraction (am I saying that right??), round the number and divide by the same number. So if you want to round to half places, you would do this:

1. flip 1/2 around to make it 2/1 (or 2)
2. multiply by the number you want to round
3. round the result from step 2
4. divide the result from step 3 by the number you got in step 1 (2 in this case)

Lets start with the first one in my example and run through the steps:

1. 2/1 => 2
2. 5.6 * 2 => 11.2
3. 11.2.round => 11
4. 11 / 2.0 => 5.5

And here it is in a Ruby method:

So you can pass any fraction to this method and it will round to that fraction. For example, you can try this with 20ths:

round_to_fraction(2.224, 1.0/20.0)
=> 2.2

round_to_fraction(2.225, 1.0/20.0)
=> 2.25

Remember to add the .0 to the end of the numbers you are dividing, so it forces ruby to treat it as a float. 1.0 / 20.0