Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for only digits in VB.NET String

Tags:

vb.net

I want to run a check on a String right before I append it to a StringBuilder to make sure only numeric characters are in the string. What's a simple way to do that?

like image 906
Scott Avatar asked Jul 30 '10 19:07

Scott


3 Answers

Use Integer.TryParse() it will return true if there are only digits in the string. Int32 max value is 2,147,483,647 so if your value is less then that then your fine. http://msdn.microsoft.com/en-us/library/f02979c7.aspx

You can also use Double.TryParse() which has a max value of 1.7976931348623157E+308 but it will allow a decimal point.

If your looking to get the value that isnt an integer you can always go through the string one at a time

string test = "1112003212g1232";
        int result;
        bool append=true;
        for (int i = 0; i < test.Length-1; i++)
        {
            if(!Int32.TryParse(test.Substring(i,i+1),out result))
            {
                //Not an integer
                append = false;
            }
        }

If append stays true then the string is an integer. Probably a more slick way of doing this but this should work.

like image 129
Gage Avatar answered Oct 23 '22 03:10

Gage


Coding in VB.Net to check whether a string contains only numeric values or not.

If IsNumeric("your_text") Then
  MessageBox.Show("yes")
Else
  MessageBox.Show("no")
End If
like image 23
mickle sharma Avatar answered Oct 23 '22 03:10

mickle sharma


Use regular expressions:

Dim reg as New RegEx("^\d$")

If reg.IsMatch(myStringToTest) Then
  ' Numeric
Else
  ' Not
End If

UPDATE:

You could also use linq to accomplish the same task if you're doing it in VB.Net 2008/2010.

Dim isNumeric as Boolean = False

Dim stringQuery = From c In myStringToTest 
                          Where Char.IsDigit(c) 
                          Select c

If stringQuery.Count <> myStringToTest.Length Then isNumeric = False
like image 40
Joel Etherton Avatar answered Oct 23 '22 02:10

Joel Etherton