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.
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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With