65.9K
CodeProject is changing. Read more.
Home

Asymmetric Arithmetic Rounding

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.36/5 (8 votes)

Oct 29, 2004

viewsIcon

45869

downloadIcon

1

.NET uses Bankers rounding. Want to bring back the rounding they taught you in grade school? This simple bit of code will help!

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;

    //Shift the decimal to the right the number 
    //of digits they want to round to
    for (int i = 1; i <= numOfDec; i++)
    {
        num *= 10;
    }

    //Add/Subtract .5 to TRY to increase the number 
    //that is to the LEFT of the decimal
    if (num < 0)
    {
        num -= .5M;
    }
    else
    {
        num += .5M;
    }

    //Cut off the decimal, you have your answer!
    num = (decimal)((int)num);

    //Shift the decimal back into its proper position
    for (int i = 1; i <= numOfDec; i++)
    {
        num /= 10;
    }

    return num;

}