หลายวิธีตรวจสอบว่าสตริงประกอบด้วยตัวเลขเท่านั้น
วิธีที่ 1: LINQ All + Char.IsDigit (Simple)
using System;
using System.Linq;
string str = "3456";
bool isNumber = str.All(c => char.IsDigit(c)); // True
string str2 = "34a6";
bool isNumber2 = str2.All(c => char.IsDigit(c)); // False
วิธีที่ 2: int.TryParse / long.TryParse (แนะนำ - รองรับ Negative, Overflow)
string str = "3456";
bool success = int.TryParse(str, out int value);
// success = true, value = 3456
string str2 = "-3456";
success = int.TryParse(str2, out value); // True, -3456
string str3 = "345678901234567890";
success = long.TryParse(str3, out long lval); // True (64-bit)
string str4 = "3.14";
success = int.TryParse(str4, out value); // False (Decimal Point)
วิธีที่ 3: double/decimal.TryParse (รองรับทศนิยม)
string str = "3.14159";
bool success = double.TryParse(str, out double value); // True
// กำหนด Culture/Style
success = double.TryParse("1,234.56", NumberStyles.Number, CultureInfo.InvariantCulture, out value);
// success = True, value = 1234.56
วิธีที่ 4: Regex (Pattern Matching)
using System.Text.RegularExpressions;
// Integer Only
bool isInt = Regex.IsMatch(str, @"^\d+$"); // Positive Only
bool isIntSigned = Regex.IsMatch(str, @"^-?\d+$"); // With Optional -
// Decimal
bool isDecimal = Regex.IsMatch(str, @"^-?\d+(\.\d+)?$");
ตารางเปรียบเทียบ
| Method | รองรับ - | รองรับ Decimal | Overflow Safe | Performance | Use Case |
|---|---|---|---|---|---|
| All(IsDigit) | ✗ | ✗ | N/A | Fast | Positive Integers Only |
| int.TryParse | ✓ | ✗ | ✓ | Fast | General Integer |
| long.TryParse | ✓ | ✗ | ✓ | Fast | Large Integers |
| double.TryParse | ✓ | ✓ | ✓ | Medium | Floating Point |
| decimal.TryParse | ✓ | ✓ | ✓ | Medium | Financial/Precision |
| Regex | ✓ | ✓ | N/A | Slow | Complex Patterns |
Extension Method สำหรับ Reuse
public static class StringExtensions
{
public static bool IsInteger(this string s) =>
!string.IsNullOrEmpty(s) && s.All(char.IsDigit);
public static bool IsNumber(this string s) =>
double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out _);
public static bool TryParseInt(this string s, out int value) =>
int.TryParse(s, out value);
public static int? ToIntOrNull(this string s) =>
int.TryParse(s, out int v) ? v : null;
}
กรณีใช้งานจริง
- Input Validation (Forms, API)
- Parsing Config/CLI Arguments
- CSV/Log Parsing
- Game Dev: High Score Parsing
⚠️ ข้อควรระวัง
char.IsDigitรองรับ Unicode Digits (٠١٢٣...) - อาจไม่ใช่ที่ต้องการint.TryParseไม่รองรับ Group Separator (1,000) โดย Default- Empty String: `All` คืน True, `TryParse` คืน False
- Whitespace: `TryParse` คืน False ถ้าไม่ Trim