public static bool IsNumeric(string input)
{
if (string.IsNullOrWhiteSpace(input)) return false;
return double.TryParse(input, out _);
}
此呼叫等同 double.TryParse(input, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out _)。
| 旗標 | 允許內容 | 範例 |
|---|---|---|
| None | 純數字 | "123" |
| AllowLeadingWhite | 前導空白 | " 123" |
| AllowTrailingWhite | 尾隨空白 | "123 " |
| AllowLeadingSign | 正負號 | "+123", "-123" |
| AllowTrailingSign | 尾部正負號 | "123-" (罕見) |
| AllowParentheses | 括號表示負數 | "(123)" → -123 |
| AllowDecimalPoint | 小數點 | "123.45" |
| AllowThousands | 千分位分隔符 | "1,234,567" |
| AllowExponent | 科學標記法 | "1.23E+4" |
| AllowCurrencySymbol | 貨幣符號 | "$123", "NT$123" |
| Float | AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | 通用浮點數 |
| Number | Float | AllowThousands | AllowParentheses | 通用數值 |
| Currency | Number | AllowCurrencySymbol | 貨幣數值 |
| Any | 除 AllowHexSpecifier 外所有 | 最寬鬆 |
public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out double result);
s:輸入字串。style:NumberStyles 位元組合,控制允許格式。provider:CultureInfo 或 NumberFormatInfo,決定小數點、千分位、貨幣符號等字元。result:輸出參數,轉換成功為數值,失敗為 0。using System.Globalization;
string[] tests = { "1,234.56", "-987", " 3.14 ", "(100)", "1.23E-4", "$123", "NT$456" };
foreach (var t in tests)
{
bool ok = double.TryParse(t, NumberStyles.Currency, CultureInfo.GetCultureInfo("zh-TW"), out double val);
Console.WriteLine($"{t,-15} → {ok,-5} {val}");
}
// 輸出 (zh-TW 文化特性):
// 1,234.56 → True 1234.56
// -987 → True -987
// 3.14 → True 3.14
// (100) → True -100
// 1.23E-4 → True 0.000123
// $123 → False 0 (zh-TW 貨幣符號為 NT$)
// NT$456 → True 456
public static bool IsInteger(string input)
{
return int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out _);
// NumberStyles.Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign
}
| 方法 | 耗時 (ms) | 備註 |
|---|---|---|
| double.TryParse (預設) | ~180 | 最推薦,平衡功能與速度 |
| double.TryParse (NumberStyles.Any) | ~210 | 解析較多規則稍慢 |
| Regex.IsMatch(@"^\\d+$") | ~420 | 正則表達式較慢,且功能有限 |
| char.All(c => char.IsDigit(c)) | ~90 | 最快但僅限正整數、無正負號 |
TryParse(null, ...) 回傳 false,result=0,不拋例外。"1.234" 在 de-DE 為 1234 (千分位),在 en-US 為 1.234 (小數)。跨文化傳輸必須指定 CultureInfo.InvariantCulture 或固定格式。double.MaxValue 回傳 false,不拋 OverflowException。原文連結:https://www.bianceng.cn/Programming/csharp/201410/45583.htm