↑ Grab this Headline Animator

Friday, February 26, 2010

MS Excel like Round function in c#.

1. Excel Round function behaves differently when we compare with C# Math.Round() method.
2. Also Excel Round allows Round to -1, -2... example Round(121,-1) = 120. This is not allowed in Math.Round()
3. Say if we want to Round 1234.5678 to nearest integer value then Math.Round() returns 1234 where as MS Excel Round gives 12345.
4. Below is a C# function that gives similar result as MS Excel Round and also allows negative rounding.

public double roundNum(double num, int place)
double n;
n = num * Math.Pow(10, place);
n = Math.Sign(n) * Math.Abs(Math.Floor(n + .5));
return n / Math.Pow(10, place);

Note: Visual Studio 2005 allows us to mention Round Up or Round down for Math.Round() method.

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.


Latest Articles