The following code snippet demonstrates what you want. It uses a technique of multiplying by two (so that what we round to then becomes a whole number) and taking off a tiny amount. We subtract the 0.001M because we want 0.25 to round to 0 and 0.75 to round to 0.5. Normally when rounding after multiplying by two they would be rounded up. Takign the small amount off ensures that we are rounding 0.499 and 1.499 to get 0 and 1 which then give the right result when divided by two. The two midpoint rounding techniques offered, away form zero and to even will not do what we want here.
public decimal MyRound(decimal input)
{
return Math.Round(input*2-0.001M, MidpointRounding.AwayFromZero)/2;
}
void Main()
{
var testvalues = new decimal[]{0M,0.125M,0.25M,0.375M,0.5M,0.625M,0.75M,0.875M,1M};
foreach (var value in testvalues)
{
Console.WriteLine(String.Format("{0} rounds to {1}",value, MyRound(value)));
}
}
Output:
0 rounds to 0
0.125 rounds to 0
0.25 rounds to 0
0.375 rounds to 0.5
0.5 rounds to 0.5
0.625 rounds to 0.5
0.75 rounds to 0.5
0.875 rounds to 1
1 rounds to 1
I should note that I used decimal just because I had it in my brain that this was what you were using (I think because my brain had "decimal places" in it. The technique will work just as well for doubles...