1

I have value as belowbelow

string value = "10053409434400003333336533210923";

When I try to parse below it isNumeric displays always false result because of long (i think)

long n;
bool isNumeric = long.TryParse(value , out n);
if (!isNumeric) // Always false
{

}

Where I miss in code how can I check string (even 50 characters) value is numeric or not ?

Thanks

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
Richard
  • 137
  • 1
  • 1
  • 12
  • Your code and your question shows/tells different things. Your code try to parse your `string` to `long` which returns `false` because your value is too big for `long` type. Your question says; _how can I check string value is numeric_ which I guess you try to check every character is numeric or not which is _already_ [have a question](http://stackoverflow.com/questions/4524957/how-to-check-if-my-string-only-numeric). Can you please clarify your question? – Soner Gönül Apr 30 '15 at 07:32
  • 1
    You also didn't say whether you want to allow a negative value. The LINQ and regex methods in the answers will fail to recognize that. – Dirk Apr 30 '15 at 07:34
  • Parsing does even more job than simply going through string character by character. Your solution to the problem is similar to one when you convert `int x` to `string` and test its `Lengh` to see if `x > 9 && x < 100`. Correct approach is given by @AlexD answer. – Sinatr Apr 30 '15 at 07:39
  • @SonerGönül yine sallamaya basladın amk – Richard Apr 30 '15 at 07:56

4 Answers4

13

If you want to check if all characters are digits, without making sure that the number can be represented by an integral type, try Linq:

bool digitsOnly = s.All(c => char.IsDigit(c));
AlexD
  • 32,156
  • 3
  • 71
  • 65
6

If you want to be able to use the parsed number, you will need a type large enough to represent it. A .NET long can support –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 so I suggest using BigInteger (add a reference to System.Numerics)

BigInteger number1;
bool succeeded1 = BigInteger.TryParse("10053409434400003333336533210923", out number1);

BigInteger.TryParse

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
2

You can try this solution : https://stackoverflow.com/a/894567/1793453

Regex.IsMatch(input, @"^\d+$")
Community
  • 1
  • 1
Edward N
  • 997
  • 6
  • 11
2

The long type is 64 bit and can only hold values from –9223372036854775808 to 9223372036854775807.

You could use a Regex instead:

Regex regex = new Regex(@"^\d+$");
BaBu
  • 1,923
  • 2
  • 16
  • 27