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

4
  • 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. Can you please clarify your question? Commented Apr 30, 2015 at 7: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. Commented Apr 30, 2015 at 7: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. Commented Apr 30, 2015 at 7:39
  • @SonerGönül yine sallamaya basladın amk Commented Apr 30, 2015 at 7:56

4 Answers 4

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));
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

You will need a reference to System.Numerics for this to work.
yes you are right that's my fault but your code is ok thanks for help
2

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

Regex.IsMatch(input, @"^\d+$")

Comments

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+$");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.