Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is this string numeric?

Status
Not open for further replies.

KoRUPT

Programmer
Jul 25, 2002
25
CA
Is there a function that checks strings for only numbers? psuedo code example:

//I know that these namespaces dont exist.. just giving you an idea of what I want
System.IsNumeric("88338k33"); //returns false
System.IsNumeric("9303 39"); //returns false
System.IsNumeric("929229"); //returns true

I saw something like this for characters but not for strings.

Thanks.
 
Straight from help....

Public Function IsNumeric(ByVal Expression As Object) As Boolean
Parameter
Expression
Required. Object expression.
Remarks
IsNumeric returns True if the entire Expression is recognized as a number; otherwise, it returns False.

IsNumeric returns True if the data type of Expression is Short, Integer, Long, Decimal, Single, or Short. It also returns True if Expression is a String that can be successfully converted to a Double. It returns False if Expression is of data type Date.

Example
This example uses the IsNumeric function to determine if the contents of a variable can be evaluated as a number.

Dim MyVar As Object
Dim MyCheck As Boolean
' ...
MyVar = "53" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "459.95" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "45 Help" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns False.

Craig
 
That would help me A LOT, if I was posting in a VB forum ;)

Anyone have an C# solutions?

Thanks
 
[translated to c#]
object MyVar;
boolean MyCheck;

// ...
MyVar = "53"; // Assign value.
MyCheck = IsNumeric(MyVar); // Returns True.
// ...
MyVar = "459.95"; // Assign value.
MyCheck = IsNumeric(MyVar); // Returns True.
// ...
MyVar = "45 Help"; // Assign value.
MyCheck = IsNumeric(MyVar); // Returns False.

[author Craig]

 
That does not work either. If someone could tell me which namespace the IsNumeric() function is in, then it should work.

Thank you.
 
sorry my fault. In c# it's IsNumber. Here is the example

using System;

public class IsNumberSample {
public static void Main() {
string str = "non-numeric";

Console.WriteLine(Char.IsNumber('8')); // Output: "True"
Console.WriteLine(Char.IsNumber(str, 3)); // Output: "False"
}
}
 
Hmmm... so I guess the only way is to do it a character at a time. Thanks for your help. I'll do it this way.
 
KoRUPT -

The 2nd overload for the IsNumber function accepts a string, so no need to do it a character at a time. Take a look at:

ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemCharClassIsNumberTopic.htm

Chip H.
 
Yes it does accept a string. It also accepts an integer specifying the character to check. So you DO have to do it a character at a time;

From the Help:
Indicates whether the character at the specified position in a specified string is categorized as a decimal digit or hexadecimal number.

[C#] public static bool IsNumber(string, int);


Example:
using System;

public class IsNumberSample {
public static void Main() {
string str = "889n999";
Console.WriteLine(Char.IsNumber('8')); //Output: "True"
Console.WriteLine(Char.IsNumber(str, 3)); //Output: "False"
Console.WriteLine(Char.IsNumber(str, 2)); //Output: "True"
}
}
 
Uh-Oh. You're right.
Character at a time it is.

Maybe you could wrapper it in a static method to make it easier to use.

Chip H.
 
That check is not so difficult to do.
This function will return true if the string only has numbers.

private bool CheckForNumeric(string s)
{
bool onlynumber = false;

for (int i=0; i<s.Length; i++)
{
int keyInt = (int)s;
//Only numbers between 48 and 57.
if ( keyInt < 48 || keyInt > 57)
onlynumber = true;
else
return false;
}
return onlynumber;
}

CheckForNumeric(&quot;4567&quot;); returns true;
CheckForNumeric(&quot;45j345&quot;); returns false;

Larsson
 
A method that I've been using is to try and convert it to a number using the System.Int32.Parse() method. If it isn't a number, it will throw an exception which you can catch and return a false instead.

AS
 
Using int32.Parse() and catching the exception contains way too much overhead. On operations in which it passes it will be quick, on failures you're going to take a performance hit..

I did two tests, one with an int.Parse() catching the exception and another in which i turned the string into a char array and looped over each character and did char.IsNumeric() (see code below).. i did each 40,000 times with 3 failures and 1 pass, the resulting int.parse took 37 seconds to complete all 40,000 operations, the 2nd solution took 0.02 seconds. These of course are extreme situations but gives you a good idea on what to expect under increased load.

private static bool IsNumeric(string Source)
{
try
{
int.Parse(Source);
return true;
}
catch(Exception)
{
return false;
}
}

private static bool IsNumeric2(string Source)
{
foreach(char CurrentCharacter in Source.ToCharArray())
{
if (!char.IsNumber(CurrentCharacter))
return false;
}

return true;
}


 
You can also do this using a regular expression. This would allow you to check for a specific kind of number:
Integer, Decimal, Negative/Non-Negative.

Regular expressions are very powerful for evaluating strings.




here is some example code:

using System.Text.RegularExpressions;

bool valid = true;

string regExp = GetRegExp(); // Build your expression
if ( !Regex.IsMatch(this.Text, regExp ) )
valid = false;

return valid;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top