How do I round to the nearest 0.5?

Murtaza Mandvi picture Murtaza Mandvi · Aug 25, 2009 · Viewed 123k times · Source

I have to display ratings and for that i need increments as follows:

If the number is 1.0 it should be equal to 1
If the number is 1.1 should be equal to 1
If the number is 1.2 should be equal to 1
If the number is 1.3 should be equal to 1.5
If the number is 1.4 should be equal to 1.5
If the number is 1.5 should be equal to 1.5
If the number is 1.6 should be equal to 1.5
If the number is 1.7 should be equal to 1.5
If the number is 1.8 should be equal to 2.0
If the number is 1.9 should be equal to 2.0
If the number is 2.0 should be equal to 2.0
If the number is 2.1 should be equal to 2.0
and so on...

Is there a simple way to compute the required values?

Answer

John Rasch picture John Rasch · Aug 25, 2009

Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero), then divide that value by 2.

Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2