Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Asymmetric Arithmetic Rounding

0.00/5 (No votes)
29 Oct 2004 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;

}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here