4

I'm trying to check if a string is a valid number or not. But this returns false. Why.

int IsNumber;
var parsed = int.TryParse("9876543210", NumberStyles.Number, null, out IsNumber);

if (parsed)
 {

 }
else
 {

 }

Also tried with CultureInfo.CurrentCulture.NumberFormat, instead of null. When debugging, it never hits inside the if condition.

4
  • 12
    the maxvalue of a 32-bit integer is 2,147,483,647. use int64/long instead Commented Aug 31, 2015 at 11:08
  • 2
    try long.TryParse, because int is max 2bilion Commented Aug 31, 2015 at 11:08
  • 2
    And if long doesn't cover the range you want, look at BigInteger... Commented Aug 31, 2015 at 11:09
  • 1
    for the future: i guess you could have find that out by using int.Parse and inspect the exception. Commented Aug 31, 2015 at 11:09

3 Answers 3

12

This should work

long IsNumber;
var parsed = long.TryParse("9876543210", NumberStyles.Number, null, out IsNumber);

if (parsed)
{

}
else
{

}

your code wasn't working because int.Max is 2147483647. If you want to check if all chars in string are digits, you can use Char.IsDigit:

var number = yourString.All(Char.IsDigit);

it will work for numbers bigger than max value of long ( 9223372036854775807)

Sign up to request clarification or add additional context in comments.

Comments

1

If you are using it for validation (as you describe it) and you don't need to convert it to number type, use regular expression instead. This regular expression gives you information, whether the string contains numbers only

var stringToValidate = "9876543210"
Regex regex = new Regex(@"^\d$");
if (regex.IsMatch(compare))
{ 
    //validation passed
}

1 Comment

You're missing a * (or +) there. Also, careful with \d - it also matches other numerals, like for example. If you only want "modern european" numbers, [0-9] really works best.
1

Use BigInteger.TryParse Method. BigInteger represents an arbitrarily large signed integer.

Add this to using directives at top of page:

using System.Numerics;

Then:

BigInteger IsNumber;
var parsed = BigInteger.TryParse("9876543210", NumberStyles.Integer, null, out IsNumber);

if (parsed)
{

}
else
{

}

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.