6

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?

2
  • 1
    Define numeric character? Do you only consider 0 to 9, or hexa decimal character too? Is 0x87 valid? Commented Jul 30, 2010 at 19:09
  • Yup only 0-9 i need to keep track of Commented Jul 30, 2010 at 19:10

9 Answers 9

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

As long as the string isn't larger than the max Int32.
That won't work if the string is too long resulting in the integer overflow
Pretty much I just want to make sure a string only has numeric characters, and IF it doesn't, I need to find the location in that string where the non-numeric character is located, and see what the value is
Yes I realize thats C#, same basic idea though
This will fail if a string represents a number below zero: eg. -1 This will be parsed as a number but what you want to actually check is if the string is digits-only. For finite accuracy and assumptions on string length, at least check if it's negative.
8

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

Comments

4

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

1 Comment

Regular Expressions is the more elegant solution IMHO. We use RE for most of our input validation and data scrubbing.
3

If you do not wish to use RegEx, a simple check on each character with char.IsNumber works.

You can combine it with the All extension method (in C#, I don't know how to write it in VB.net):

string value = "78645655";
bool isValid = value.All(char.IsNumber);

Check out other char method, like IsDigit.

1 Comment

Unfortunately VB won't let you write something as elegant. You'd end up with value.All(Function(c) Char.IsNumber(c))
3

2 other compact solutions :

Without LINQ :

Dim foo As String = "10004"
Array.Exists(foo.ToCharArray, Function(c As Char) Not Char.IsNumber(c))

With LINQ (just VB.Net equivalent of the C# version in another answer) :

foo.All(Function(c As Char) Char.IsNumber(c))

Comments

2

Negative values haven't been mentioned, which Integer.TryParse would accept.

I prefer UInteger.TryParse which will reject a negative number. However, there is an additional check required in case the value starts with "+":

Dim test As String = "1444"
Dim outTest As UInteger
If Not test.StartsWith("+") AndAlso UInteger.TryParse(test, outTest) Then
    MessageBox.Show("It's just digits!")
End If

or ULong.TryParse for a larger number.

Comments

1

Pattern matching! See this, this (about.com) and this (VB.NET dev article).

Comments

1

You can use regular expression or Integer.TryParse and I prefer the regular expression check

Comments

1

Presuming you're looking at relatively short strings which will never have a number greater than the Max Int32 value, use Gage's solution. If it's a variable length and sometimes you could overflow, use Regex (System.Text.RegularExpressions)

The regex for checking against just numbers is fairly routine: ^[0-9]+$

Check here for a very good explanation of Regex.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.