Reputation: 3665
There are the obvious quirks of Math.Round
but is there a way to make Math.Round
fulfill this type of manipulation for a rating system.
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
So obviously a half star would be .5
and a whole start would be the next whole value.
I don't know of a rounding method to go to half whole numbers.
Should I just write if statements to control my rounding?
**Edit/Solution
From the below answer I came up with.
double roundedRating = (Math.Ceiling(2 * currentRating)) / 2;
Upvotes: 1
Views: 2340
Reputation: 4423
I'd recommend multiplying by two, performing Math.Ceiling
, and dividing by two to get to the nearest half.
Upvotes: 17
Reputation: 26386
Can this work?
Multiply the number by 10 e.g. 0.1x10, 0.2x10
to get n
Math.Ceil(n / 5) / 2
where n = 1, 2, 3 instead of - .1, .2, .3
examples:
1,2,3,4,5 = 1/2 = 0.5
6,7,8,9,10 = 2/2 = 1
11,12,13,14,15 = 3/2 = 1.5
Upvotes: 1
Reputation: 39085
double roundedRating = (int)(currentRating * 2D + 0.999999999999999) / 2D
Upvotes: 0
Reputation: 13054
If efficiency is no issue, the following approach could be used:
Number *= 10;
Number % 10 = remainder;
if(remainder <=5 && remainder != 0)
//Half star
else
//Whole star
However, that code is kinda ugly, but I think it gives you the general idea.
Upvotes: 0
Reputation: 5504
You're going to want to make sure that you end up performing your checks against integers, rather than floating point numbers.
Start by multiplying the number by 2. Continue doing this until it's an integer value (no value in the decimal part).
Now, continuously divide by 2 until you end up with a number that's less than or equal to the original number. If the result decimal part is greater than .0 and less than or equal to .5, display half a star. If it's greater than .5 and less than or equal to +.0, display a whole star.
Actually, go with matt's answer. ; )
Upvotes: 2