Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a number with different resolutions

Tags:

c#

rounding

With C# I need an elegant way to round a number with a resolution of 1/8 to a resolution of 1/2 with the following rules:

Round(0) = 0
Round(0.125) = 0
Round(0.25) = 0
Round(0.375) = 0.5
Round(0.5) = 0.5
Round(0.625) = 0.5
Round(0.75) = 0.5
Round(0.875) = 1
Round(1) = 1

Of course that I'm not limited to only numbers between 0 and 1. Is there a good way to do it without too many ifs?

like image 611
Yonatan Nir Avatar asked Nov 22 '25 00:11

Yonatan Nir


1 Answers

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...

like image 104
Chris Avatar answered Nov 23 '25 13:11

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!