首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 判斷字串是否為數字:double.TryParse 完整用法與 NumberStyles 解析

     編輯:關於C#

標準做法:double.TryParse

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 _)。

進階控制:NumberStyles 列舉

旗標允許內容範例
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"
FloatAllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent通用浮點數
NumberFloat | AllowThousands | AllowParentheses通用數值
CurrencyNumber | 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

整數專用:int.TryParse / long.TryParse

public static bool IsInteger(string input)
{
    return int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out _);
    // NumberStyles.Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign
}

效能比較 (100 萬次迴圈)

方法耗時 (ms)備註
double.TryParse (預設)~180最推薦,平衡功能與速度
double.TryParse (NumberStyles.Any)~210解析較多規則稍慢
Regex.IsMatch(@"^\\d+$")~420正則表達式較慢,且功能有限
char.All(c => char.IsDigit(c))~90最快但僅限正整數、無正負號

常見陷阱

  • Null/空字串: 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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved