Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int.TryParse returns false when parsing a valid string

Tags:

c#

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.

like image 342
Qwerty Avatar asked Oct 24 '25 02:10

Qwerty


2 Answers

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)

like image 54
Kamil Budziewski Avatar answered Oct 26 '25 16:10

Kamil Budziewski


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
}
like image 26
David Gregor Avatar answered Oct 26 '25 18:10

David Gregor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!