怎样在C#中判断字符串为纯数字类型的

2024-11-28 06:30:23
推荐回答(1个)
回答1:

有个方法(但不一定是最好的方法)。见以下程序中的IsNumberic方法

using System;

namespace ConsoleApplication1
{
    class Program
    {
      
        static void Main(string[] args)
        {
            string s = "122.2";
            if (IsNumeric(s))
            {
                Console.WriteLine("{0}是纯数字", s);
            }
            else
            {
                Console.WriteLine("{0}不是纯数字", s);
            }

            s = "12a356";
            if (IsNumeric(s))
            {
                Console.WriteLine("{0}是纯数字", s);
            }
            else
            {
                Console.WriteLine("{0}不是纯数字", s);
            }

        }
        
        // 判断字符串是否为纯数字
        static bool IsNumeric(string s)
        {
            double v;
            if(double.TryParse(s, out v))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}