If I have these strings:
"abc"
=false
"123"
=true
"ab2"
=false
Is there a command, like IsNumeric or something else, that can identify if a string is a valid number?
If I have these strings:
"abc"
= false
"123"
= true
"ab2"
= false
Is there a command, like IsNumeric or something else, that can identify if a string is a valid number?
The best flexible solution with .net built-in function called-
char.IsDigit
. It works with unlimited long numbers. It will only return true if each character is a numeric number. I used it lot of times with no issues and much easily cleaner solution I ever found. I made a example method.Its ready to use. In addition I added validation for null and empty input. So the method is now totally bulletproofHere is the C# method. Int.TryParse Method (String, Int32)
If you want to know if a string is a number, you could always try parsing it:
Note that
TryParse
returns abool
, which you can use to check if your parsing succeeded.Double.TryParse
If you want to check if a string is a number (I'm assuming it's a string since if it's a number, duh, you know it's one).
you could also do:
This will take care of the usual nasties:
contains decimal characterBigIntegers won't parse numbers with decimal points. (So:BigInteger.Parse("3.3")
will throw an exception, andTryParse
for the same will return false)Double.TryParse
You'll have to add a reference to
System.Numerics
and haveusing System.Numerics;
on top of your class (well, the second is a bonus I guess :)Use these extension methods to clearly distinguish between a check if the string is numerical and if the string only contains 0-9 digits