Rounding has always been a bit of a struggle. Recently I had a requirement to do some rounding for a rating type of system (i.e. x / 5 stars). As it has been long know, the Math.Round method handles .5 a bit differently than we would like. So let’s take a look at the specific requirements and dig into this example a bit deeper.
If greater than .0 and less than or equal to .5, display half a star If greater than .5 and less than or equal to .0 display whole star
This made for a little bit of a trickier approach since we are want a value such as 1.1 to round to 1.5 and then wanting 1.7 to round to 2.0. When you start breaking it apart it’s not too bad. We are going to take advantage of the Math.Ceiling method. Math.Ceiling returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number. In a real basic sense it’s going to round the number up. So in our context of ratings, the following ratings of say 1.2, 1.7, and 1.9 all will round up to 2. How does this help us? Let’s take a look at the line doing our rounding.
double roundedRating = (Math.Ceiling(2 * currentRating)) / 2;
I think the easiest way to understand is to plug in some numbers. Lets run an example. So per our requirements, we would expect 1.1 to give us a final rounded rating of 1.5.
double roundedRating = (Math.Ceiling(2 * 1.1)) / 2; double roundedRating = (Math.Ceiling(2.2)) / 2; double roundedRating = (3) / 2; double roundedRating = 1.5;
Following through the logic above, by doubling our initial rating, we are allowing ourselves to round to a whole number, and then divide that in half to achieve our .5 rating system that is required. Overall, not entirely complicated but turned out to be a helpful little method to round to either .5 or .0 depending on the initial rating.