Home > Software engineering >  Check if the string "00" is a number and return false in C#
Check if the string "00" is a number and return false in C#

Time:11-13

I need to check if a string is a number and then I need to check the arrange of this number. So I use the TryParse method for it but I need for strings "00" or "01" or similiar get false. With my code I get true:

var isNum = int.TryParse(s, out int n);

So I have a trouble with such strings ("00", "01" etc) because I got true but I want to get false

CodePudding user response:

you can also add a check if (s.StartsWith("0") == false). so it will return false for all the strings with leading 0.

so you can use the code.

bool isNum = s.StartsWith("0") == false && int.TryParse(s, out int n);

CodePudding user response:

Try this

var isNum = !s.StartsWith("0") && int.TryParse(s, out int n);

CodePudding user response:

simply (reverse-) compare the result as a string afterwards:

var isNum = int.TryParse(s, out int n);
isNum = n.ToString().Equals(s) 

This assures in any case (and with the correct comparison in any culture) that s is a true int.

  • Related