C# seems to lack function that PHP has

  • Thread starter Thread starter harrylmh
  • Start date Start date
H

harrylmh

I want to check if a string "123" is a number. but C# seems to lack a
method tat does tat. the closest is char.isNumber where you can only
check one character at a time anyway.

Anyone knows a way around this? Or is there a method to do this
already?

Thanks
 
harrylmh said:
I want to check if a string "123" is a number. but C# seems to lack a
method tat does tat. the closest is char.isNumber where you can only
check one character at a time anyway.

Anyone knows a way around this? Or is there a method to do this
already?

Well, you can try to parse it using Int32.Parse or Convert.ToInt32, and
catch the exception. Or you can use Double.TryParse with appropriate
options. Or you can use a simple home-grown method which checks for
every character being between 0 and 9 (to get rid of "simple"
violations) and then use either of the other options to check more
complicated things. I've found this hybrid approach to be the fastest
in simple benchmarking scenarios.
 
See if this function helps you..

private bool IsNumeric(string strNum)
{
try
{
Double.Parse(strNum);
return true;
}
catch
{
return false;
}
}

Regards
Benny
 
You could use a simple regex also:

return (Regex.IsMatch(inputString, "[0-9]"));

HTH,
Bill P.
 
Double.TryParse() will do it.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Bill P. said:
You could use a simple regex also:

return (Regex.IsMatch(inputString, "[0-9]"));

HTH,
Bill P.


harrylmh said:
I want to check if a string "123" is a number. but C# seems to lack a
method tat does tat. the closest is char.isNumber where you can only
check one character at a time anyway.

Anyone knows a way around this? Or is there a method to do this
already?

Thanks
 
Back
Top