How can I check if a string is a number?

后端 未结 25 1860
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 21:04

I\'d like to know on C# how to check if a string is a number (and just a number).

Example :

141241   Yes
232a23   No
12412a   No

an

25条回答
  •  悲哀的现实
    2020-11-27 21:30

    I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.

        private bool IsValidNumber(string _checkString, string _checkType)
        {
            float _checkF;
            int _checkI;
            bool _result = false;
    
            switch (_checkType)
            {
                case "int":
                    _result = int.TryParse(_checkString, out _checkI);
                    break;
                case "float":
                    _result = Single.TryParse(_checkString, out _checkF);
                    break;
            }
            return _result;
    
        }
    

    I simply call this with something like:

    if (IsValidNumber("1.2", "float")) etc...
    

    It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.

提交回复
热议问题