Welcome :Guest

Congratulations!!!

Top 5 Contributors of the Month
sritaa
Sandeep Singh
Melody Anderson
Eminent IT

 Home >> Code Snippets >> Regular Expressions >> Post New Resource

# IsNumeric function to check integer / numeric value

Posted By:Amit Mehra       Posted Date: October 08, 2009    Points: 10    Category: Regular Expressions    URL: http://www.dotnetspark.com

### IsNumeric function to check integer / numeric value in C#, Vb.Net.

These function you can use to validate if the input string or object is Numeric or Not. Below are the 2 ways to check the Input as string and Output of the method is boolean.

Lets see the 1st method

Method 1: With Regular expression we can check that Given value is integer or not. Below function also check with minus sign of integer value

//Method to Check the given string is integer or not

In C#

`//Method to Check the given string is integer or notpublic static bool IsNumeric(String strVal){Regex reg = new Regex("[^0-9-]");Regex reg2 = new Regex("^-[0-9]+\$|^[0-9]+\$");return (!reg.IsMatch(strVal) && reg2.IsMatch(strVal));}      `

In Vb.NET

`'Method to Check the given string is integer or notPublic Shared Function IsNumeric(ByVal strVal As [String]) As BooleanDim reg As New Regex("[^0-9-]")Dim reg2 As New Regex("^-[0-9]+\$|^[0-9]+\$")Return (Not reg.IsMatch(strVal) AndAlso reg2.IsMatch(strVal))End Function`

Method 2: This is another method to validate the string is numeric value or not. This method is not advisable when you are checking the large amount of data because Exception is be costly.

in C# Code Example

`bool IsNumeric(string strVal){try{double doub = double.Parse(strVal);return true;catch{return false;}}`

In Vb.Net

`Private Function IsNumeric(ByVal strVal As String) As BooleanTryDim doub As Double = Double.Parse(strVal)Return TrueCatchReturn FalseEnd TryEnd Function`

Again if you are dealing with huge amount of data inside loop than Method 1 is the best choice as method 1 used regular expression to check the numeric value hence faster approach.

There are so many ways to check above are the 2 of them

Thanks
Amit

Responses
Author: Santosh         Company URL: http://www.dotnetspark.com
Posted Date: October 08, 2009

hi
Follow Below Links u will get some code,like the above validation code posted by Amit

http://www.dotnetspark.com/kb/Content.aspx?id=904
http://santoshdotnetarena.blogspot.com/2009/10/to-validate-textbox-decimal-values.html

Santosh
http://santoshdotnetarena.blogspot.com

Post Comment