is my string a number ?

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

I want to efficiently test whether an arbitrary string contains an integer
value. I know I can try to execute Int32.Parse on it and capture the
exception but I'd like by code to be a bit cleaner.
 
bool digit = true;
foreach(char c in stringToTest)
{
if(!Char.IsDigit(c))
digit = false;
}
 
JezB said:
I want to efficiently test whether an arbitrary string contains an integer
value. I know I can try to execute Int32.Parse on it and capture the
exception but I'd like by code to be a bit cleaner.

Search for "Checking if a string can be converted to Int32" on
groups.google.com - I benchmarked various different ways of doing this
a while ago.
 
JezB said:
I want to efficiently test whether an arbitrary string contains an integer
value. I know I can try to execute Int32.Parse on it and capture the
exception but I'd like by code to be a bit cleaner.

If I were you, I'd just write my own function that uses Int32.Parse() in its
implementation. The other solutions presented here so far are either not
efficient (regular expressions?) or incomplete (they don't account for
leading whitespace, the sign, and the fact that the number of digits may be
too many).
 
Hi Jezb,

JezB said:
I want to efficiently test whether an arbitrary string contains an integer
value. I know I can try to execute Int32.Parse on it and capture the
exception but I'd like by code to be a bit cleaner.

I'd suggest looking at Double.TryParse. It doesn't throw an exception
(returns true or false). It has a NumberStyles parameter that allows you to
be very specific about what format you are expecting. A minor point: You can
also get the parsed value without an extra function call (via an "out"
parameter).

Regards,
Dan
 
Daniel Pratt said:
I'd suggest looking at Double.TryParse. It doesn't throw an exception
(returns true or false). It has a NumberStyles parameter that allows you to
be very specific about what format you are expecting. A minor point: You can
also get the parsed value without an extra function call (via an "out"
parameter).

This is still less efficient than having some custom code to throw out
obviously dodgy ones. In my sample benchmark, a hard-coded check
followed by Int32.Parse was over 50 times faster than using
Double.TryParse. It depends on the data used though.
 
Back
Top