# Recipe 6.19. Determining if a String Contains a Valid Number

#### Problem

You want to verify that a user-entered string contains a valid number.

#### Solution

Use Visual Basic's IsNumeric() function to check the string.

#### Discussion

Visual Basic 2005 provides a function named IsNumeric() that checks the content of any string, returning a Boolean true if the string contains a valid number representation and False if it doesn't:

` Dim result As New System.Text.StringBuilder Dim testString As String testString = "2.E3" result.Append(testString).Append(vbTab) result.AppendLine(IsNumeric(testString).ToString) testString = "2.D3" result.Append(testString).Append(vbTab) result.AppendLine(IsNumeric(testString).ToString) testString = "-123" result.Append(testString).Append(vbTab) result.AppendLine(IsNumeric(testString).ToString) testString = "-1 2 3" result.Append(testString).Append(vbTab) result.AppendLine(IsNumeric(testString).ToString) testString = "\$54.32" result.Append(testString).Append(vbTab) result.AppendLine(IsNumeric(testString).ToString) MsgBox(result.ToString()) `

Currency values are valid numbers, even with the currency symbol included. The IsNumeric() function expects a single number in the string, so extra spaces, such as those shown in the next-to-last string in the example, cause IsNumeric() to return False. If you want to determine how many valid numbers are in a string, and be able to grab them all, consider using regular expressions instead.

Figure 6-19 shows the strings used in this example and the results returned by IsNumeric() for each.

##### Figure 6-19. Testing whether a string contains a valid number using IsNumeric( )

Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon