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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With