I have simple function checking if string is number or not. Suddenly I discovered that it don't work with "0" or "00". Tell me why, please! And how to make it works?
string num = "00";
Int32.TryParse(num, out int n);
if (n > 0) return true; // It works nice on any digits except 0 and 00.
Also I tried:
double.TryParse(num, out double n);
But don't work too.
So I went in such way:
if ((n > 0) | (num == "0") | (num == "00")) return true;
CodePudding user response:
Of course 0 is not greater than 0, what did you expect? :)
int.TryParse
returns a boolean letting you know if parsing the number was successful:
Returns
Boolean
true
ifs
was converted successfully; otherwise,false
.
So what you oughta do is the following:
return int.TryParse(num, out int _);
CodePudding user response:
You can create a function and call it to check if it is a number or not.
class Program
{
static void Main(string[] args)
{
string num = "00";
if (IsNumber(num))
Console.WriteLine($"'{num}' is a number");
else
Console.WriteLine($"'{num}' is not a number");
}
private static bool IsNumber(string num)
{
return int.TryParse(num, out _);
}
}