[C#] 實作 IsNumeric

  • 4017
  • 0

[C#] 實作 IsNumeric

又是亂逛,發現 MSDN 有示範如何判斷是否為數字的範例。

連結 :  http://support.microsoft.com/kb/329488/zh-tw

 

    class Program {
        static void Main(string[] args) {
            // Test a numeric string. 
            Console.WriteLine("\"123\" is numeric : {0}", IsNumeric("123"));
            // Test a number.
            Console.WriteLine("-5.64 is numeric : {0}", IsNumeric(-5.64));
            // Test infinity.
            Console.WriteLine("-Infinity is numeric : {0}", IsNumeric("-Infinity"));
            // Test infinity.
            Console.WriteLine("Infinity is numeric : {0}", IsNumeric("Infinity"));
            // Test a general string.
            Console.WriteLine("\"12ABC\" is numeric : {0}", IsNumeric("12ABC"));
            // Test with null.
            Console.WriteLine("null is numeric : {0}", IsNumeric(null));

            Console.WriteLine("\"000000.0000001\" is numeric : {0}", IsNumeric("000000.0000001"));

            Console.Read();		
        }

        // IsNumeric Function
        static bool IsNumeric(object Expression) {
            // Variable to collect the Return value of the TryParse method.
            bool isNum;

            // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
            double retNum;

            // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
            // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
            isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            return isNum;
        }		
    }
}

 

輸出結果

2010-01-07_111540

三小俠  小弟獻醜,歡迎指教