I want a rounding method on double values in C#. It needs to be able to round a double value to any rounding precision value. My code on hand looks like:
pub
If you actually need to use double just replace it below and it will work but with the usual precision problems of binary floating-point arithmetics.
There's most certainly a better way to implement the "rounding" (almost a kind of bankers' rounding) than my string juggling below.
public static decimal RoundI(decimal number, decimal roundingInterval)
{
if (roundingInterval == 0) { return 0;}
decimal intv = Math.Abs(roundingInterval);
decimal modulo = number % intv;
if ((intv - modulo) == modulo) {
var temp = (number - modulo).ToString("#.##################");
if (temp.Length != 0 && temp[temp.Length - 1] % 2 == 0) modulo *= -1;
}
else if ((intv - modulo) < modulo)
modulo = (intv - modulo);
else
modulo *= -1;
return number + modulo;
}