C# IsNumeric Method equivalent to VB

0 votes
asked Jun 11, 2013 in C#.NET by anonymous
edited Jun 11, 2013

What is the equivalent method in C# for IsNumeric Validation method which we have in VB. If there is no such a method, what would be the best way to implment that?

Share

1 Answer

+1 vote
answered Jun 11, 2013 by Aadhira (1,213 points)
selected Jun 11, 2013 by administrator
 
Best answer

I don't think we have any exact matching method for IsNumeric in C#. Also, I am not sure whether the below method is the perfect solution, but it works for me so good so far in my applications.
I have included some condition to check NaN, Infinity, because TryParse of Double will return true if the string is "Nan" or "Infinity". But In my case, it is not a valid numeric. So, I am validating that as well.

public class IsNumericValidation
{
        public static bool IsNumeric(string anyString)
        {
            bool isNumeric = false;
            Double outValue;
            isNumeric = Double.TryParse(anyString, out outValue);
            if (isNumeric)
            {
                isNumeric = !(Double.IsNaN(outValue) ||
                                Double.IsInfinity(outValue) ||
                                Double.IsPositiveInfinity(outValue) ||
                                Double.IsNegativeInfinity(outValue));
            }
            return isNumeric;
        }
}

I test with the below values and the result was same as I expect for my scenario.

static void Main(string[] args)
{
            Console.WriteLine(IsNumericValidation.IsNumeric("any string"));
            Console.WriteLine(IsNumericValidation.IsNumeric("NaN"));
            Console.WriteLine(IsNumericValidation.IsNumeric("Infinity"));
            Console.WriteLine(IsNumericValidation.IsNumeric("12"));
            Console.WriteLine(IsNumericValidation.IsNumeric("12.345893745"));
            Console.WriteLine(IsNumericValidation.IsNumeric("89475347935789475279037402794728903492"));
            Console.WriteLine(IsNumericValidation.IsNumeric("-0.78234792"));
            Console.WriteLine(IsNumericValidation.IsNumeric("74835794.348975349"));
            Console.Read();
}

Output:
Result for first 3 values are False and rest all true.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...