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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# equivilant to VB.NET IsNumeric function 2

Status
Not open for further replies.

meckeard

Programmer
Aug 17, 2001
619
US
Does C# have am equivilant to VB.NET's IsNumeric() function?

Googled it and I only found a function the loops thru a string and checks each character. But I have a huge form with textbox values that need to be numeric values and I don't want to use the extra resources doing it this way.

Any idea?

Thanks.
 
This is one thing that can be done, although it's not pretty:
Code:
public static bool IsInteger(string testValue){
    try{
        int x = Int32.Parse(testValue);
    }catch{
        return false;
    }
    return true;
}

[pipe]
 
You can always reference and import Microsoft.VisualBasic - then you get all the VB functions

Mark [openup]
 
Wow - using the Regex is WAY faster than the try/parse method. I tested it 1,000,000 times each (with failing test string) and the try/parse method took 35 seconds, 453 miliseconds and the regex way took 1 second, 156 miliseconds! (P4 3GHz). I can post test app code if anyone wants.

[pipe]
 
dragonwell gets a star for testing possible solutions to see which would be a better fit.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Reg Exp are cool, but I would suspect that the reason the code is so much faster than the try parse method is not how fast regexp are, but simply the fact that the try parse method relies on throwing an exception. Even throwing 1 million exceptions, without doing anything else, will cause this kind of performance.

By the way, you're going to need a better pattern than "[09]" to mimic IsNumeric. I would start with
^\d+\.?\d+?$
which means some digits, then optionally a decimal point (though of course you should really dig this out from the localized settings...), then optionally some more digits.

The ^ and $ mean that the entire string must match this - it is not enough for this pattern to be found somewhere in the string.

This does not account for a string like "1E-08", which is numeric according to IsNumeric, but will not pass this pattern.

You could try one of the regular expression libraries on line.

Good luck.



Mark [openup]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top