private bool IsNumeric(string text) {
try { int.Parse(text); return true; }
catch { return false; }
}
TryParse 時的權宜之計public bool IsNumber(string str) {
var notNumber = new Regex(@"[^0-9.-]");
var twoDot = new Regex(@"[0-9]*\.[0-9]*\.[0-9]*");
var twoMinus = new Regex(@"[0-9]*-[0-9]*-[0-9]*");
var validReal = @"^([-]|[.]|[-.]|[0-9])[0-9]*\.?[0-9]+$";
var validInt = @"^([-]|[0-9])[0-9]*$";
var numberPattern = new Regex($"({validReal})|({validInt})");
return !notNumber.IsMatch(str)
&& !twoDot.IsMatch(str)
&& !twoMinus.IsMatch(str)
&& numberPattern.IsMatch(str);
}
public static bool IsNumeric(string v) => Regex.IsMatch(v, @"^[+-]?\d*\.?\d*$");
public static bool IsInt(string v) => Regex.IsMatch(v, @"^[+-]?\d*$");
public static bool IsUnsigned(string v) => Regex.IsMatch(v, @"^\d*\.?\d*$");
public bool IsNumeric(string s) {
foreach (char c in s) if (c < '0' || c > '9') return false;
return s.Length > 0;
}
public static bool IsNumeric(string s) {
s = s.Trim();
bool hasDigit = false, hasDot = false;
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (char.IsDigit(c)) { hasDigit = true; continue; }
if (c == '.' && !hasDot) { hasDot = true; continue; }
if (i == 0 && (c == '+' || c == '-')) continue;
return false;
}
return hasDigit;
}
完整移植包含十六進位/八進位辨識、文化特性數值格式解析,程式碼量大,維護成本高,不建議直接複製。
using Microsoft.VisualBasic;
bool isNum = Information.IsNumeric("123");
社區回饋指出關鍵問題:
「第二、三種方法未檢查數值範圍。用
999...999(50 位數) 通過IsInt,但int.Parse會拋例外;同理double.Parse也會失敗。」
結論:格式驗證與數值轉換應合併,直接使用 TryParse 同時完成兩者。
int.TryParse / double.TryParse / decimal.TryParse —— 標準、高效、同時完成驗證與轉換Regex + TryParse 雙重檢查Parse+try-catch、VB 移植、VisualBasic.dll 依賴public bool TryParseInput(string input, out double value) {
// 1. 快速前置檢查:長度、空白、明顯非數字字元
if (string.IsNullOrWhiteSpace(input) || input.Length > 50) {
value = 0; return false;
}
// 2. 核心驗證+轉換
return double.TryParse(input, NumberStyles.Float | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out value);
}
「字串是否為數字」看似簡單,實則涉及格式定義、文化特性、數值範圍、效能權衡。選對工具,才能寫出正確又快速的程式碼。