Introduction
.NET rounding is limited to bankers rounding. I searched far and wide for an alternative. I didn't find one. There may be better ways to do this, but I believe this is pretty lightweight and simple.
The Scoop: 1 - 4: rounds down, 5 - 9: rounds up. Simply add these functions to a class or a form or whatever you are programming, and call them whenever you need to do rounding.
public static float aaRounding(float numToRound, int numOfDec)
{
return (float)aaRounding((decimal)numToRound, numOfDec);
}
public static double aaRounding(double numToRound, int numOfDec)
{
return (double)aaRounding((decimal)numToRound, numOfDec);
}
public static decimal aaRounding(decimal numToRound, int numOfDec)
{
if (numOfDec < 0)
{
throw new ArgumentException("BetterMath.Rounding:" +
" Number of decimal places must be 0 or greater",
"numOfDec");
}
decimal num = numToRound;
for (int i = 1; i <= numOfDec; i++)
{
num *= 10;
}
if (num < 0)
{
num -= .5M;
}
else
{
num += .5M;
}
num = (decimal)((int)num);
for (int i = 1; i <= numOfDec; i++)
{
num /= 10;
}
return num;
}