A better alternative to solving the rounding mechanism in your apps

Awhile back, I wrote a blog post on the rounding mechanism, little did I know that a reader posted a better alternative in the comments (I should read keep track of the comments closely in the future). I haven't tested this, but I trust the contributor of this piece of code. Full credit goes to gohsianghwee for posting this, and I quote him:

There is a better alternative, pass in the value 1234.23 and round digit as 2 will solve your problem. This algorithm makes user definable rounding possible. In fact, I just showed you one of my rounding mechanism in my application, which all rounding mechanism in my application are user definable.

User must always use decimal in terms of dollar and cent calculation. Even though decimal is not a primitive type, but it handles the calculation more appropriately compared to the others. This is due to how .NET handles primitive type figures.

public static decimal RoundAmount(decimal roundValue, decimal roundDigit)

{

decimal totalValue = 0;

decimal powerValue = 0;

powerValue = (decimal)(System.Math.Pow(10, (double)roundDigit));

decimal tempDecimalValue = 5 / powerValue;

decimal rndFigure = roundValue / tempDecimalValue;

totalValue =(decimal)(System.Math.Round(rndFigure, 0)) * tempDecimalValue;

return totalValue;

}

Thanks!